Skip to content

Commit

Permalink
Add polling for transaction status
Browse files Browse the repository at this point in the history
* replace getRecentBlockhash with getLatestBlockhash
* replace confirmTransaction with getSignatureStatus
* add basic polling mechanism for a submitted transaction
  • Loading branch information
bfriel committed Jul 1, 2022
1 parent 633931a commit 0366d59
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,34 @@ export default function App() {
})
);
transaction.feePayer = provider.publicKey;
addLog("Getting recent blockhash");
addLog("Getting latest blockhash");
const anyTransaction: any = transaction;
anyTransaction.recentBlockhash = (
await connection.getRecentBlockhash()
await connection.getLatestBlockhash()
).blockhash;
return transaction;
};

// A simple helper function used to space out our signature polling
const pause = (ms: number) => new Promise((res) => setTimeout(res, ms));

const pollSignatureStatus = async (signature: string) => {
const maxPolls = 10;
for (let pollCount = 0; pollCount < maxPolls; pollCount++) {
const { value } = await connection.getSignatureStatus(signature);
if (value?.confirmationStatus) {
addLog(`Transaction ${signature} ${value.confirmationStatus}`);
if (
value.confirmationStatus === "confirmed" ||
value.confirmationStatus === "finalized"
)
return;
}
await pause(1000);
}
addLog(`Failed to confirm transaction ${signature}`);
};

const signAndSendTransaction = async () => {
try {
const transaction = await createTransferTransaction();
Expand All @@ -145,8 +165,7 @@ export default function App() {
signature +
", awaiting confirmation..."
);
await connection.confirmTransaction(signature);
addLog("Transaction " + signature + " confirmed");
pollSignatureStatus(signature);
} catch (err) {
console.warn(err);
addLog("[error] signAndSendTransaction: " + JSON.stringify(err));
Expand Down

0 comments on commit 0366d59

Please sign in to comment.