Last active
December 12, 2024 20:20
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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