Skip to content

Instantly share code, notes, and snippets.

@stegaBOB
Last active April 22, 2024 15:42
Show Gist options
  • Save stegaBOB/7c0cdc916db4524dd9c285f9e4309475 to your computer and use it in GitHub Desktop.
Save stegaBOB/7c0cdc916db4524dd9c285f9e4309475 to your computer and use it in GitHub Desktop.
Gets an optimal transaction with priority fees and minimum CU limits in parallel with Promise.all
async function getPriorityFees(instructions: TransactionInstruction[]): Promise<number> {
// replace with real function
return 426;
}
async function getSimulationUnits(
connection: Connection,
instructions: TransactionInstruction[],
payer: PublicKey,
lookupTables: AddressLookupTableAccount[]
): Promise<number | undefined> {
const testInstructions = [
ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }),
...instructions,
];
const testVersionedTxn = new VersionedTransaction(
new TransactionMessage({
instructions: testInstructions,
payerKey: payer,
recentBlockhash: PublicKey.default.toString(),
}).compileToV0Message(lookupTables)
);
const simulation = await connection.simulateTransaction(testVersionedTxn, {
replaceRecentBlockhash: true,
sigVerify: false,
});
if (simulation.value.err) {
return undefined;
}
return simulation.value.unitsConsumed;
}
async function buildOptimalTransaction(
connection: Connection,
instructions: TransactionInstruction[],
signer: Signer,
lookupTables: AddressLookupTableAccount[]
) {
const [microLamports, units, recentBlockhash] = await Promise.all([
getPriorityFees(instructions),
getSimulationUnits(connection, instructions, signer.publicKey, lookupTables),
connection.getLatestBlockhash(),
]);
instructions.unshift(ComputeBudgetProgram.setComputeUnitPrice({ microLamports }));
if (units) {
// probably should add some margin of error to units
instructions.unshift(ComputeBudgetProgram.setComputeUnitLimit({ units }));
}
return {
transaction: new VersionedTransaction(
new TransactionMessage({
instructions,
recentBlockhash: recentBlockhash.blockhash,
payerKey: signer.publicKey,
}).compileToV0Message(lookupTables)
),
recentBlockhash,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment