wait until the transaction gets max confirmations
This file contains 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
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