import type { Connection, TransactionInstruction } from "@solana/web3.js"; import { ComputeBudgetProgram } from "@solana/web3.js"; export const estimatePriorityFees = async ( connection: Connection, instructions: TransactionInstruction[], multiplier = 1, maxPriorityFee = 100000, minPriorityFee = 1, ): Promise => { const accounts = instructions.flatMap((e) => e.keys).map((e) => e.pubkey); const prioFees = await connection.getRecentPrioritizationFees({ lockedWritableAccounts: accounts, }); // Sort in descending order on slot so we get the latest data prioFees.sort((a, b) => b.slot - a.slot); // Estimate priority fee by taking the avg of recent fees and scale with the provider multiplier // to control speed/likelyhood of success const estimatedPrioFee = Math.floor( (multiplier * prioFees .slice(0, 10) .map((e) => e.prioritizationFee) .reduce((a, b) => a + b, 0)) / prioFees.length, ); // Apply min and max cap if needed const prioFee = Math.max( minPriorityFee, Math.min(estimatedPrioFee, maxPriorityFee), ); const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({ microLamports: prioFee, }); return addPriorityFee; };