Skip to content

Instantly share code, notes, and snippets.

@Shaneumayanga
Created February 6, 2025 12:51
Show Gist options
  • Save Shaneumayanga/901085912bba6421e7875abeb3d42a69 to your computer and use it in GitHub Desktop.
Save Shaneumayanga/901085912bba6421e7875abeb3d42a69 to your computer and use it in GitHub Desktop.
transaction sender and waiter for solana
async function transactionSenderAndConfirmationWaiter({
serializedTransaction,
blockhashWithExpiryBlockHeight,
maxRetryTimeMs = 60000,
}) {
const startTime = Date.now();
const txid = await connection.sendRawTransaction(
serializedTransaction,
{
skipPreflight: true,
}
);
const controller = new AbortController();
const abortSignal = controller.signal;
const abortableResender = async () => {
while (Date.now() - startTime < maxRetryTimeMs) {
await wait(2000);
if (abortSignal.aborted) return;
try {
console.log("resending....");
await connection.sendRawTransaction(serializedTransaction, {
skipPreflight: true,
});
} catch (e) {
console.warn(`Failed to resend transaction: ${e}`);
}
}
};
try {
abortableResender();
const lastValidBlockHeight = blockhashWithExpiryBlockHeight.lastValidBlockHeight;
await Promise.race([
connection.confirmTransaction(
{
...blockhashWithExpiryBlockHeight,
lastValidBlockHeight,
signature: txid,
},
"confirmed"
),
new Promise(async (resolve) => {
while (!abortSignal.aborted) {
await wait(2000);
const tx = await connection.getSignatureStatus(txid, {
searchTransactionHistory: false,
});
if (tx?.value?.confirmationStatus === "confirmed") {
resolve(tx);
}
}
}),
]);
} catch (e) {
if (e instanceof TransactionExpiredBlockheightExceededError) {
return null;
} else {
throw e;
}
} finally {
controller.abort();
}
const response = await promiseRetry(
async (retry) => {
const response = await connection.getTransaction(txid, {
commitment: "confirmed",
maxSupportedTransactionVersion: 0,
});
if (!response) {
retry(response);
}
return response;
},
{
retries: 5,
minTimeout: 1000,
}
);
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment