import { toBN, dedupArray } from "../../utils";
import { compileTransaction, } from "@solana/kit";
/**
 * @notice Returns result of getFeeForMessage and getRecentPrioritizationFees RPC calls.
 * @returns GasPriceEstimate
 */
export async function messageFee(provider, opts) {
    const { unsignedTx: _unsignedTx } = opts;
    // Cast the opaque unsignedTx type to a solana-kit TransactionMessage with fee payer.
    const unsignedTx = _unsignedTx;
    const compiledTransaction = compileTransaction(unsignedTx);
    // Get this base fee. This should result in LAMPORTS_PER_SIGNATURE * nSignatures.
    const encodedTransactionMessage = Buffer.from(compiledTransaction.messageBytes).toString("base64");
    const baseFeeResponse = await provider.getFeeForMessage(encodedTransactionMessage).send();
    // Get the priority fee by calling `getRecentPrioritzationFees` on all the addresses in the transaction's instruction array.
    const instructionAddresses = dedupArray(unsignedTx.instructions.map((instruction) => instruction.programAddress));
    const recentPriorityFees = await provider.getRecentPrioritizationFees(instructionAddresses).send();
    // Take the most recent 25 slots and find the average of the nonzero priority fees.
    const nonzeroPrioritizationFees = recentPriorityFees
        .slice(125)
        .map((value) => value.prioritizationFee)
        .filter((fee) => fee > 0);
    const totalPrioritizationFees = nonzeroPrioritizationFees.reduce((acc, fee) => acc + fee, BigInt(0));
    const microLamportsPerComputeUnit = toBN(totalPrioritizationFees / BigInt(Math.max(nonzeroPrioritizationFees.length, 1)));
    return {
        baseFee: toBN(baseFeeResponse.value),
        microLamportsPerComputeUnit,
    };
}
//# sourceMappingURL=solana.js.map