Skip to content

Commit

Permalink
Replace confirmTx function
Browse files Browse the repository at this point in the history
  • Loading branch information
jacksondoherty committed Nov 17, 2024
1 parent 1f3d276 commit 53800a9
Showing 1 changed file with 50 additions and 16 deletions.
66 changes: 50 additions & 16 deletions common/js/tx-sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
PublicKey,
Transaction,
Connection,
SignatureStatus,
} from "@solana/web3.js";

import { interpretTxErr, InterpretedTxErrType } from "./tx-error";
Expand Down Expand Up @@ -147,11 +148,53 @@ async function createOptimizedV0Tx(
return { v0Tx, lastValidBlockHeight };
}

// Replacement for Agave 2.0
async function confirmTx(
connection: Connection,
sig: string
): Promise<SignatureStatus> {
return new Promise((resolve, reject) => {
// eslint-disable-next-line prefer-const
let intervalId: NodeJS.Timeout | undefined;
// eslint-disable-next-line prefer-const
let timeoutId: NodeJS.Timeout | undefined;

const checkStatus = async (): Promise<void> => {
try {
const status = (await connection.getSignatureStatuses([sig])).value[0];

if (
status !== null &&
(status.confirmationStatus === "confirmed" ||
status.confirmationStatus === "finalized" ||
status.err !== null)
) {
clearInterval(intervalId);
clearTimeout(timeoutId);
resolve(status);
}
} catch (err) {
clearInterval(intervalId);
clearTimeout(timeoutId);
console.error("Error confirming transaction", err);
reject(err);
}
};

checkStatus();

intervalId = setInterval(checkStatus, 400);

timeoutId = setTimeout(() => {
clearInterval(intervalId);
reject(new TypeError("Confirm transaction timed out"));
}, 2 * 60 * 1000); // 2 minutes
});
}

async function broadcastAndConf(
connection: Connection,
rawTx: Uint8Array,
blockhash: string,
lastValidBlockHeight: number
rawTx: Uint8Array
): Promise<string> {
// Send transaction
let intervalId: NodeJS.Timeout | undefined;
Expand All @@ -174,13 +217,9 @@ async function broadcastAndConf(

// Confirm transaction
console.log("Confirming...");
const confirmation = await connection.confirmTransaction({
signature: sig,
blockhash,
lastValidBlockHeight,
});
if (confirmation.value.err) {
throw new Error(`${confirmation.value.err.toString()}`);
const res = await confirmTx(connection, sig);
if (res.err) {
throw new Error(`${res.err.toString()}`);
}

console.log(`Transaction confirmed: https://explorer.solana.com/tx/${sig}`);
Expand Down Expand Up @@ -218,12 +257,7 @@ async function simSignSignAndConf(
const rawTx = signedTx.serialize();

console.log("Sending...");
const sig = await broadcastAndConf(
connection,
rawTx,
signedTx.message.recentBlockhash,
lastValidBlockHeight
);
const sig = await broadcastAndConf(connection, rawTx);
return sig;
}

Expand Down

0 comments on commit 53800a9

Please sign in to comment.