"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.redeemOnAlgorand = exports.redeemOnSolana = exports.redeemAndUnwrapOnSolana = exports.redeemOnTerra = exports.redeemOnEthNative = exports.redeemOnEth = exports.redeemOnAlph = void 0;
const web3_1 = require("@alephium/web3");
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 scripts_1 = require("../alephium-contracts/ts/scripts");
const algorand_1 = require("../algorand");
const ethers_contracts_1 = require("../ethers-contracts");
const solana_1 = require("../solana");
const wasm_1 = require("../solana/wasm");
const utils_1 = require("../utils");
const array_1 = require("../utils/array");
const vaa_1 = require("../utils/vaa");
function redeemOnAlph(signerProvider, tokenBridgeForChainId, signedVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        return scripts_1.CompleteTransfer.execute(signerProvider, {
            initialFields: {
                tokenBridgeForChain: tokenBridgeForChainId,
                vaa: web3_1.binToHex(signedVAA)
            },
            attoAlphAmount: web3_1.DUST_AMOUNT * BigInt(2)
        });
    });
}
exports.redeemOnAlph = redeemOnAlph;
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;
function redeemAndUnwrapOnSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, signedVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        const { complete_transfer_native_ix } = yield wasm_1.importTokenWasm();
        const parsedVAA = vaa_1.deserializeTransferTokenVAA(signedVAA);
        const parsedPayload = parsedVAA.body.payload;
        const targetAddress = array_1.hexToNativeString(array_1.uint8ArrayToHex(parsedPayload.targetAddress), utils_1.CHAIN_ID_SOLANA);
        if (!targetAddress) {
            throw new Error("Failed to read the target address.");
        }
        const targetPublicKey = new web3_js_1.PublicKey(targetAddress);
        const targetAmount = parsedPayload.amount *
            BigInt(utils_1.WSOL_DECIMALS - utils_1.MAX_VAA_DECIMALS) *
            BigInt(10);
        const rentBalance = yield spl_token_1.Token.getMinBalanceRentForExemptAccount(connection);
        const mintPublicKey = new web3_js_1.PublicKey(utils_1.WSOL_ADDRESS);
        const payerPublicKey = new web3_js_1.PublicKey(payerAddress);
        const ancillaryKeypair = web3_js_1.Keypair.generate();
        const completeTransferIx = solana_1.ixFromRust(complete_transfer_native_ix(tokenBridgeAddress, bridgeAddress, payerAddress, 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.AccountLayout.span,
            programId: spl_token_1.TOKEN_PROGRAM_ID,
        });
        //Initialize the account as a WSOL account, with the original payerAddress as owner
        const initAccountIx = yield spl_token_1.Token.createInitAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, mintPublicKey, ancillaryKeypair.publicKey, payerPublicKey);
        //Send in the amount of wSOL which we want converted to SOL
        const balanceTransferIx = spl_token_1.Token.createTransferInstruction(spl_token_1.TOKEN_PROGRAM_ID, targetPublicKey, ancillaryKeypair.publicKey, payerPublicKey, [], new spl_token_1.u64(targetAmount.toString(16), 16));
        //Close the ancillary account for cleanup. Payer address receives any remaining funds
        const closeAccountIx = spl_token_1.Token.createCloseAccountInstruction(spl_token_1.TOKEN_PROGRAM_ID, ancillaryKeypair.publicKey, //account to close
        payerPublicKey, //Remaining funds destination
        payerPublicKey, //authority
        []);
        const { blockhash } = yield connection.getRecentBlockhash();
        const transaction = new web3_js_1.Transaction();
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = new web3_js_1.PublicKey(payerAddress);
        transaction.add(completeTransferIx);
        transaction.add(createAncillaryAccountIx);
        transaction.add(initAccountIx);
        transaction.add(balanceTransferIx);
        transaction.add(closeAccountIx);
        transaction.partialSign(ancillaryKeypair);
        return transaction;
    });
}
exports.redeemAndUnwrapOnSolana = redeemAndUnwrapOnSolana;
function redeemOnSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, signedVAA, feeRecipientAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        const { parse_vaa } = yield wasm_1.importCoreWasm();
        const parsedVAA = parse_vaa(signedVAA);
        const isSolanaNative = Buffer.from(new Uint8Array(parsedVAA.payload)).readUInt16BE(65) ===
            utils_1.CHAIN_ID_SOLANA;
        const { complete_transfer_wrapped_ix, complete_transfer_native_ix } = yield wasm_1.importTokenWasm();
        const ixs = [];
        if (isSolanaNative) {
            ixs.push(solana_1.ixFromRust(complete_transfer_native_ix(tokenBridgeAddress, bridgeAddress, payerAddress, signedVAA, feeRecipientAddress)));
        }
        else {
            ixs.push(solana_1.ixFromRust(complete_transfer_wrapped_ix(tokenBridgeAddress, bridgeAddress, payerAddress, signedVAA, feeRecipientAddress)));
        }
        const transaction = new web3_js_1.Transaction().add(...ixs);
        const { blockhash } = yield connection.getRecentBlockhash();
        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;
