Skip to content

Instantly share code, notes, and snippets.

@0xMukesh
Created December 15, 2022 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xMukesh/4f0f6855f926fa793d936d4c77cf9790 to your computer and use it in GitHub Desktop.
Save 0xMukesh/4f0f6855f926fa793d936d4c77cf9790 to your computer and use it in GitHub Desktop.
wait until the transaction gets max confirmations
import { test } from "vitest";
import {
clusterApiUrl,
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
} from "@solana/web3.js";
import pRetry from "p-retry";
import base58 from "bs58";
import dotenv from "dotenv";
dotenv.config();
test.skip("promise", async () => {
const connection = new Connection(clusterApiUrl("devnet"));
const payer = Keypair.fromSecretKey(
base58.decode(process.env.DEV_SECRET_KEY!)
);
const receiver = new PublicKey(process.env.RECEIVER!);
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: receiver,
lamports: 0.005 * LAMPORTS_PER_SOL,
})
);
const signature = await sendAndConfirmTransaction(
connection,
transaction,
[payer],
{
commitment: "processed", // it is processed so won't actually show the transaction metadata instantly
}
);
console.log(`Signature - ${signature}`);
// this is the logic which waits until the transaction is confirmed/finalized and returns the transaction metadata
const transactionMetadata = await pRetry(
async () => {
const fetchedTransactionMetadata = await connection.getTransaction(
signature
);
return fetchedTransactionMetadata !== null
? fetchedTransactionMetadata
: Promise.reject(new Error("Transaction isn't confirmed yet"));
},
{
retries: 5,
}
);
console.log(JSON.stringify(transactionMetadata));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment