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 { PublicKey } from "@solana/web3.js";
/*
    The transactions provided to this function should be ready to be sent.
    This function will only add the feePayer and blockhash, and then sign, send, and confirm the transaction.
*/
export function sendAndConfirmTransactionsWithRetry(connection, signTransaction, payer, unsignedTransactions, maxRetries = 0) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!(unsignedTransactions && unsignedTransactions.length)) {
            return Promise.reject("No transactions provided to send.");
        }
        let currentRetries = 0;
        let currentIndex = 0;
        const transactionReceipts = [];
        while (!(currentIndex >= unsignedTransactions.length) &&
            !(currentRetries > maxRetries)) {
            let transaction = unsignedTransactions[currentIndex];
            let signed = null;
            try {
                const { blockhash } = yield connection.getRecentBlockhash();
                transaction.recentBlockhash = blockhash;
                transaction.feePayer = new PublicKey(payer);
            }
            catch (e) {
                console.error(e);
                currentRetries++;
                //Behavior after this is undefined, so best just to restart and try again.
                continue;
            }
            try {
                signed = yield signTransaction(transaction);
            }
            catch (e) {
                //Eject here because this is most likely an intentional rejection from the user, or a genuine unrecoverable failure.
                return Promise.reject("Failed to sign transaction.");
            }
            try {
                const txid = yield connection.sendRawTransaction(signed.serialize());
                const receipt = yield connection.confirmTransaction(txid);
                transactionReceipts.push(receipt);
                currentIndex++;
            }
            catch (e) {
                console.error(e);
                currentRetries++;
            }
        }
        if (currentRetries > maxRetries) {
            return Promise.reject("Reached the maximum number of retries.");
        }
        else {
            return Promise.resolve(transactionReceipts);
        }
    });
}
