services
Get a key

library / Blockchain ideas / Payment tools / BI0097

Safe-retry payment check

A check to run before any retry. Give it a signature and its lastValidBlockHeight and it answers landed, still live or expired. Runnable read-only code, with the heights printed beside each verdict, so a payments backend never pays twice.

By Carbium · Payment tools · BI0097 · updated 2026-11-22

01

What the error means

A Solana transaction names a recent blockhash, and the network accepts it only while that blockhash is young. getLatestBlockhash returns the blockhash together with a lastValidBlockHeight: the last block height at which a transaction carrying it can still be included. Once the chain's block height passes that number, no validator will include the transaction.

TransactionExpiredBlockheightExceededError is what the web3.js confirmation helper throws when it sees the block height cross that line before it sees the signature confirmed. Kit's block height confirmation raises its own error for the same condition. The error reports that the wait ended. Whether the payment landed is a separate question, and the error cannot answer it.

For a payments backend that gap is where money is lost. The usual handler catches the error, signs a new transaction with a fresh blockhash and sends it. A new transaction has a new signature, so the chain has no reason to reject it as a duplicate. If the first transaction landed while your watcher was disconnected, slow or looking at a lagging node, the customer is paid twice.

VerdictWhat the reads showWhat the backend does
Landedthe signature has a statusrecord the payment and never re-sign; read err to see whether it ran or failed
Still liveno status, and the block height is at or below lastValidBlockHeightwait, or rebroadcast the same signed bytes; sign nothing new
Expiredno status, and the block height is above lastValidBlockHeightsign a fresh transaction with a fresh blockhash
$A transaction that landed and failed on chain still pays a fee and moves no funds. The check reports it as landed with the failure shown, and a fresh payment is then a new decision made after reading err.
02

The two reads that decide

getSignatureStatuses with searchTransactionHistory set to true is the first call. Without that flag the node answers from its cache of recent statuses, and a null can mean the cache forgot the signature. With it the node also looks into its ledger. The method takes no commitment argument. Each status that comes back carries its own confirmationStatus, and a status at processed can still be dropped with its fork, so release an order on confirmed or finalized.

The second call is getBlockHeight. The check reads it at finalized, so an expired verdict rests on a height no fork can take back. Every call in main.ts that takes a commitment names it, because kit fills in confirmed when a call leaves it out.

Block height and slot are different counters. A slot its leader never produced adds no block, so the block height trails the slot number and the gap grows over time. lastValidBlockHeight compares only against getBlockHeight. Compare it with getSlot and the check declares expiry too early, and the backend pays twice.

Read order matters too. The check reads the height first and the status second. A transaction that lands between the two reads then shows up in the status. Reverse the order and a payment can land after the status read and before the height read, and the check reports expired for a payment that exists.

The lastValidBlockHeight has to come from signing time. Store it with the signature when you build the message, from the same getLatestBlockhash response that gave you the blockhash. A value computed later, or a guessed constant for the blockhash's lifetime, gives a verdict that looks exact and is not.

03

The build

One file with @solana/kit and Node 24. It is read-only: no private key, nothing signed or sent. Pass a signature and its lastValidBlockHeight and it prints one verdict line. With no arguments it builds its own demo.

  1. Read the key from CARBIUM_KEY and exit with a message when it is unset.
  2. With no arguments, list the newest 100 signatures of a busy program at confirmed commitment (PROGRAM sets the address) and take the first successful one and the first failed one.
  3. Read getLatestBlockhash at confirmed and use its lastValidBlockHeight as the window for those two signatures.
  4. Add one signature that was never sent, checked against that open window and again against a window that closed long ago.
  5. For each job, read the height at finalized, then the status, and print the verdict with both heights.
main.ts
// BI0097 · Safe-retry payment check// https://carbium.sh/library/blockchainideas/safe-retry-payment-check// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";const key = process.env.CARBIUM_KEY ?? "";if (!key) {  console.error("Set CARBIUM_KEY, then run: node main.ts [<signature> <lastValidBlockHeight>]");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);async function verdict(sig: string, lastValid: bigint): Promise<string> {  // Height first, status second: a landing between the two reads then shows in the status.  const height = await rpc.getBlockHeight({ commitment: "finalized" }).send();  const { value } = await rpc.getSignatureStatuses([signature(sig)], { searchTransactionHistory: true }).send();  const st = value[0];  const heights = `block height ${height}, last valid ${lastValid}`;  if (st) return `LANDED at ${st.confirmationStatus}, slot ${st.slot}${st.err ? ", failed on chain" : ""} (${heights})`;  if (height > lastValid) return `EXPIRED, safe to re-sign (${heights})`;  return `STILL LIVE, ${lastValid - height} blocks left, rebroadcast the same bytes only (${heights})`;}async function main() {  const [sigArg, lvArg] = process.argv.slice(2);  const jobs: [string, string, bigint][] = [];  if (sigArg && lvArg) {    jobs.push(["given", sigArg, BigInt(lvArg)]);  } else {    const program = process.env.PROGRAM ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";    const [list, fresh] = await Promise.allSettled([      rpc.getSignaturesForAddress(address(program), { limit: 100, commitment: "confirmed" }).send(),      rpc.getLatestBlockhash({ commitment: "confirmed" }).send(),    ]);    if (list.status === "rejected" || fresh.status === "rejected") {      console.error("demo reads failed:", list.status === "rejected" ? String(list.reason) : "", fresh.status === "rejected" ? String(fresh.reason) : "");      process.exit(1);    }    const open = fresh.value.value.lastValidBlockHeight; // stand-in window for the demo    const ok = list.value.find((r) => r.err === null);    const bad = list.value.find((r) => r.err !== null);    if (ok) jobs.push(["landed ok", ok.signature, open]);    if (bad) jobs.push(["landed failed", bad.signature, open]);    jobs.push(["never sent, window open", "1".repeat(64), open]);    jobs.push(["never sent, window closed", "1".repeat(64), open - 1000n]);  }  for (const [label, sig, lastValid] of jobs) {    try {      console.log(`${label} ${sig.slice(0, 8)}: ${await verdict(sig, lastValid)}`);    } catch (e) {      console.log(`${label} ${sig.slice(0, 8)}: read failed, no verdict: ${e instanceof Error ? e.message : e}`);    }  }}main().catch((e) => {  console.error(e instanceof Error ? e.message : e);  process.exit(1);});

run: CARBIUM_KEY=<YOUR_KEY> node main.ts <SIGNATURE> <LAST_VALID_BLOCK_HEIGHT>

A demo run prints four lines. The two real signatures read as landed, one of them marked as failed on chain. The never-sent signature reads as still live against the open window and as expired against the closed one, which shows the two branches a real retry depends on. The listing costs 50 cells and runs once.

Each job sits in its own try, so one failing read prints its message and the loop goes on. A read that fails prints that it failed. It never prints a verdict.

04

Wiring it before every retry

  1. At signing time, write one row before anything is sent: payment id, signature, lastValidBlockHeight and the attempt number.
  2. Send, then wait for a status at confirmed.
  3. On the expiry error, a timeout or a restart, run the check on every signature recorded for that payment id.
  4. Landed: close the payment as paid, or as failed when err is set. Still live: rebroadcast the same bytes or wait. Expired on every attempt: sign again, write a new row, send.
  5. A read that throws or returns 429 gives no verdict. Treat the failure as unknown, never as expired.

A payment with two attempts is safe to re-sign only when every earlier attempt reads expired or landed with a failure. Checking only the newest signature misses the case where attempt one was slow and attempt two is the one that expired.

Do not rest the decision on a socket. A signatureSubscribe subscription sends one confirmation and then ends, so a dropped connection leaves silence, and silence is the state this check exists to resolve. Use the subscription to learn early and the check to decide. See Withdrawal confirmation tracker for tracking payouts to a final state, and Blockhash relay for offline signers for carrying a blockhash and its last valid height to a signer that is not online.

05

Where it ends

  • The check is only as good as the stored lastValidBlockHeight. With a guessed value the verdict is a guess.
  • A transaction built on a durable nonce has no blockhash expiry, so the height rule does not apply to it.
  • A null status for a signature older than the node's ledger can be a real landing. Run the check in the minutes after signing, and keep your own rows for anything older.
  • The check covers the signatures you give it. A second worker or a person who signed the same payment by hand is outside it, so keep one in-flight payment per id.
  • Landed without an error says the transaction ran. Whether the right amount reached the right account is a separate read of balances or token balances.
  • The demo borrows the latest blockhash's window for two old signatures, so its heights illustrate the printout and do not describe those transactions.
  • Nothing here sends. Rebroadcasting and re-signing stay in your payment code.
06

When it goes wrong

what goes wrongwhat to do
getSignatureStatuses answers null for a payment that did land.The call left out searchTransactionHistory, or the read reached a node that had not yet seen the block. Pass the flag and read again before acting.
The check said expired, a new payment went out, and the first one then appeared.The height was compared with a slot, read at a lower commitment, or read after the status. Compare lastValidBlockHeight only with getBlockHeight at finalized, and read the height first.
A read fails with 429.The call went over its rate. Wait for the retry-after hint and repeat the read. A failed read is no verdict.
The run exits with a message about the key.Set CARBIUM_KEY, then pass either both arguments or none.
The run stops with a message about converting to a BigInt.The second argument must be the integer lastValidBlockHeight, with no decimals, commas or quotes inside it.
The demo prints no failed-on-chain line.None of the newest 100 signatures of that program had failed. Run it again, or set PROGRAM to a busier address.
07

Questions

Can I send the same signed transaction again instead of signing a new one?

Yes, while the check says still live. The bytes carry one signature, so the chain includes them at most once, and a second broadcast of the same bytes cannot double a payment.

How many blocks does a blockhash last?

Read it from getLatestBlockhash and store the lastValidBlockHeight it returns. A constant in your code goes stale the day the rule changes, and the stored value is exact for that transaction.

The status shows a failure. Is it safe to pay again?

The failed transaction moved no funds, so a new one cannot double the payment. Read err first, because a fixable cause such as a low balance should be fixed before the new send.

Why not wait for the expiry error and then just retry?

The error comes from whichever watcher saw the height cross the line, and a watcher can run behind the chain or lose its connection. The check reads the chain again and answers from state.