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());
    });
};
import { binToHex, DUST_AMOUNT } from "@alephium/web3";
import { AccountLayout, Token, TOKEN_PROGRAM_ID, u64 } from "@solana/spl-token";
import { Keypair, PublicKey, SystemProgram, Transaction, } from "@solana/web3.js";
import { MsgExecuteContract } from "@terra-money/terra.js";
import { fromUint8Array } from "js-base64";
import { CompleteTransfer } from "../alephium-contracts/ts/scripts";
import { _submitVAAAlgorand } from "../algorand";
import { Bridge__factory } from "../ethers-contracts";
import { ixFromRust } from "../solana";
import { importCoreWasm, importTokenWasm } from "../solana/wasm";
import { CHAIN_ID_SOLANA, WSOL_ADDRESS, WSOL_DECIMALS, MAX_VAA_DECIMALS, } from "../utils";
import { hexToNativeString, uint8ArrayToHex } from "../utils/array";
import { deserializeTransferTokenVAA } from "../utils/vaa";
export function redeemOnAlph(signerProvider, tokenBridgeForChainId, signedVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        return CompleteTransfer.execute(signerProvider, {
            initialFields: {
                tokenBridgeForChain: tokenBridgeForChainId,
                vaa: binToHex(signedVAA)
            },
            attoAlphAmount: DUST_AMOUNT * BigInt(2)
        });
    });
}
export function redeemOnEth(tokenBridgeAddress, signer, signedVAA, overrides = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const bridge = Bridge__factory.connect(tokenBridgeAddress, signer);
        const v = yield bridge.completeTransfer(signedVAA, overrides);
        const receipt = yield v.wait();
        return receipt;
    });
}
export function redeemOnEthNative(tokenBridgeAddress, signer, signedVAA, overrides = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const bridge = Bridge__factory.connect(tokenBridgeAddress, signer);
        const v = yield bridge.completeTransferAndUnwrapETH(signedVAA, overrides);
        const receipt = yield v.wait();
        return receipt;
    });
}
export function redeemOnTerra(tokenBridgeAddress, walletAddress, signedVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        return new MsgExecuteContract(walletAddress, tokenBridgeAddress, {
            submit_vaa: {
                data: fromUint8Array(signedVAA),
            },
        });
    });
}
export function redeemAndUnwrapOnSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, signedVAA) {
    return __awaiter(this, void 0, void 0, function* () {
        const { complete_transfer_native_ix } = yield importTokenWasm();
        const parsedVAA = deserializeTransferTokenVAA(signedVAA);
        const parsedPayload = parsedVAA.body.payload;
        const targetAddress = hexToNativeString(uint8ArrayToHex(parsedPayload.targetAddress), CHAIN_ID_SOLANA);
        if (!targetAddress) {
            throw new Error("Failed to read the target address.");
        }
        const targetPublicKey = new PublicKey(targetAddress);
        const targetAmount = parsedPayload.amount *
            BigInt(WSOL_DECIMALS - MAX_VAA_DECIMALS) *
            BigInt(10);
        const rentBalance = yield Token.getMinBalanceRentForExemptAccount(connection);
        const mintPublicKey = new PublicKey(WSOL_ADDRESS);
        const payerPublicKey = new PublicKey(payerAddress);
        const ancillaryKeypair = Keypair.generate();
        const completeTransferIx = ixFromRust(complete_transfer_native_ix(tokenBridgeAddress, bridgeAddress, payerAddress, signedVAA));
        //This will create a temporary account where the wSOL will be moved
        const createAncillaryAccountIx = SystemProgram.createAccount({
            fromPubkey: payerPublicKey,
            newAccountPubkey: ancillaryKeypair.publicKey,
            lamports: rentBalance,
            space: AccountLayout.span,
            programId: TOKEN_PROGRAM_ID,
        });
        //Initialize the account as a WSOL account, with the original payerAddress as owner
        const initAccountIx = yield Token.createInitAccountInstruction(TOKEN_PROGRAM_ID, mintPublicKey, ancillaryKeypair.publicKey, payerPublicKey);
        //Send in the amount of wSOL which we want converted to SOL
        const balanceTransferIx = Token.createTransferInstruction(TOKEN_PROGRAM_ID, targetPublicKey, ancillaryKeypair.publicKey, payerPublicKey, [], new u64(targetAmount.toString(16), 16));
        //Close the ancillary account for cleanup. Payer address receives any remaining funds
        const closeAccountIx = Token.createCloseAccountInstruction(TOKEN_PROGRAM_ID, ancillaryKeypair.publicKey, //account to close
        payerPublicKey, //Remaining funds destination
        payerPublicKey, //authority
        []);
        const { blockhash } = yield connection.getRecentBlockhash();
        const transaction = new Transaction();
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = new PublicKey(payerAddress);
        transaction.add(completeTransferIx);
        transaction.add(createAncillaryAccountIx);
        transaction.add(initAccountIx);
        transaction.add(balanceTransferIx);
        transaction.add(closeAccountIx);
        transaction.partialSign(ancillaryKeypair);
        return transaction;
    });
}
export function redeemOnSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, signedVAA, feeRecipientAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        const { parse_vaa } = yield importCoreWasm();
        const parsedVAA = parse_vaa(signedVAA);
        const isSolanaNative = Buffer.from(new Uint8Array(parsedVAA.payload)).readUInt16BE(65) ===
            CHAIN_ID_SOLANA;
        const { complete_transfer_wrapped_ix, complete_transfer_native_ix } = yield importTokenWasm();
        const ixs = [];
        if (isSolanaNative) {
            ixs.push(ixFromRust(complete_transfer_native_ix(tokenBridgeAddress, bridgeAddress, payerAddress, signedVAA, feeRecipientAddress)));
        }
        else {
            ixs.push(ixFromRust(complete_transfer_wrapped_ix(tokenBridgeAddress, bridgeAddress, payerAddress, signedVAA, feeRecipientAddress)));
        }
        const transaction = new Transaction().add(...ixs);
        const { blockhash } = yield connection.getRecentBlockhash();
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = new PublicKey(payerAddress);
        return transaction;
    });
}
/**
 * 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)
 */
export function redeemOnAlgorand(client, tokenBridgeId, bridgeId, vaa, senderAddr) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield _submitVAAAlgorand(client, tokenBridgeId, bridgeId, vaa, senderAddr);
    });
}
