---
id: HS0099
title: "Block-height confirmation loop"
url: https://carbium.sh/library/howsolana/block-height-confirmation-loop
collection: How to use Solana
category: Confirmation and retries
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Block-height confirmation loop

One TypeScript file polls getSignatureStatuses against a lastValidBlockHeight deadline, the same exit rule as BlockheightBasedTransactionConfirmationStrategy. It checks a landed signature and a never-sent one, and prints confirmed or expired for each. It sends nothing.

## The deadline a strategy adds

`sendAndConfirmRawTransaction` in `@solana/web3.js` takes signed bytes and a confirmation strategy: the signature, the blockhash the transaction was built on, and that blockhash's `lastValidBlockHeight`. It sends, then waits for one of two events. Either the signature reaches the commitment you asked for, or the chain's block height passes `lastValidBlockHeight`. In the second case the transaction can never land, because validators reject a blockhash that has aged out of its window.

That second exit is what a fixed timeout cannot give you. A 30 second timer can fire while the transaction is still able to land, and if you then rebuild it with a fresh blockhash and send again, both versions may execute and the payer is charged twice. A block-height deadline settles the question. Once the height is past the value, the old signature is dead, and building a new transaction is safe.

The strategy is a loop around three reads, so any client can run it. `getLatestBlockhash` returns the blockhash and its `lastValidBlockHeight` together. `getBlockHeight` says where the chain is. `getSignatureStatuses` says whether the signature landed. The demo below runs that loop twice and sends nothing: once for a signature that has already landed, and once for a signature nobody ever sent, with a deadline a few blocks away. You see both exits in a few seconds.

A blockhash stays usable for 150 blocks. With a slot of about 200 ms since the Alpenglow switch, that is roughly 30 seconds of wall time. Block height trails the slot number whenever a leader skips a slot, so count blocks and never convert the window to seconds in code.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24. The optional argument is the address whose newest signatures supply the landed example. It defaults to the token program, which has activity all the time.

`main.ts` (run: `node main.ts [address]`)

```ts
// HS0099 · Block-height confirmation loop
// https://carbium.sh/library/howsolana/block-height-confirmation-loop
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import {
  address,
  createDefaultRpcTransport,
  createSolanaRpcFromTransport,
  signature,
  type Signature,
} from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url, headers: { "x-api-key": key } }),
);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

type Outcome = { state: "confirmed" | "failed" | "expired"; polls: number; detail: string };

// The strategy: stop when the signature confirms, or when block height passes the deadline.
async function waitFor(sig: Signature, lastValidBlockHeight: bigint): Promise<Outcome> {
  for (let polls = 1; ; polls++) {
    const height = await rpc.getBlockHeight({ commitment: "confirmed" }).send();
    const { value: [status] } = await rpc.getSignatureStatuses([sig]).send();
    if (status) {
      if (status.err !== null) {
        const err = JSON.stringify(status.err, (_k, v) => (typeof v === "bigint" ? v.toString() : v));
        return { state: "failed", polls, detail: `err ${err}` };
      }
      if (status.confirmationStatus === "confirmed" || status.confirmationStatus === "finalized") {
        return { state: "confirmed", polls, detail: `slot ${status.slot}, ${status.confirmationStatus}` };
      }
    } else if (height > lastValidBlockHeight) {
      return { state: "expired", polls, detail: `height ${height} is past ${lastValidBlockHeight}` };
    }
    await sleep(600);
  }
}

async function demo(label: string, sig: Signature, lastValid: bigint) {
  const started = Date.now();
  try {
    const o = await waitFor(sig, lastValid);
    console.log(`${label}: ${o.state} after ${o.polls} polls, ${Date.now() - started} ms, ${o.detail}`);
  } catch (e) {
    console.error(`${label}: poll failed: ${(e as Error).message}`);
  }
}

const busy = address(process.argv[2] ?? "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");

// 1. A signature that already landed, with the deadline a real sender would hold.
try {
  const { value: latest } = await rpc.getLatestBlockhash({ commitment: "confirmed" }).send();
  const recent = await rpc.getSignaturesForAddress(busy, { limit: 10 }).send();
  const landed = recent.find((s) => s.err === null);
  if (!landed) throw new Error("no successful signature in the newest 10");
  await demo("landed", landed.signature, latest.lastValidBlockHeight);
} catch (e) {
  console.error(`landed: setup failed: ${(e as Error).message}`);
}

// 2. A signature nobody sent, with a deadline 3 blocks ahead of the current height.
try {
  const height = await rpc.getBlockHeight({ commitment: "confirmed" }).send();
  await demo("never sent", signature("1".repeat(64)), height + 3n);
} catch (e) {
  console.error(`never sent: setup failed: ${(e as Error).message}`);
}
```

`waitFor` is the whole strategy. Each round reads the block height first and the status second. That order matters: if the status comes back empty and the height read earlier is already past the deadline, the transaction had no chance to land before the deadline, so expiry is a safe verdict. Reading in the other order leaves a gap in which the signature could land between the two calls and be reported as expired.

`getBlockHeight` and `getLatestBlockhash` ask for `confirmed`, which is also what `@solana/kit` fills in when a call leaves commitment out. `getSignatureStatuses` takes no commitment and reports the level each signature has reached. The loop accepts `confirmed` or `finalized`. Change the check to `finalized` alone when you need that level.

The landed example takes its deadline from `getLatestBlockhash`, the same value a real sender would hold. The unsent example sets the deadline at the current height plus 3. A status that comes back empty keeps the loop polling until the height passes that number, which takes about a second.

## Reading the run

Each line prints the verdict, the number of polls and the elapsed time. The first exit that fires wins, and each one calls for a different next step.

| Verdict | What the loop saw | What to do next |
|---|---|---|
| confirmed | A status at confirmed or finalized with `err` null | Treat the transaction as landed and stop. |
| failed | A status whose `err` is set | The transaction landed and failed, and the fee is paid. Read the error before building a new one. |
| expired | No status, and block height past `lastValidBlockHeight` | The signature can never land. Fetch a new blockhash, rebuild, sign and send again. |

Failed and expired are different cases. A failed transaction is on chain, so resending the same bytes changes nothing and a rebuilt copy may repeat the failure. An expired one never executed, which is why a rebuilt copy is safe to send.

> A signature you really sent goes through `waitFor` the same way: take the blockhash and its `lastValidBlockHeight` from one `getLatestBlockhash` call, sign with that blockhash, send, then pass the signature and that height in. With `@solana/web3.js` the send and the wait are one call, `sendAndConfirmRawTransaction(connection, rawTx, { signature, blockhash, lastValidBlockHeight }, { commitment: "confirmed" })`, where `signature` is the base58 of the transaction's first signature. Build the `Connection` with `httpHeaders: { "x-api-key": key }` and a `wsEndpoint` of `wss://services.carbium.sh/?api-key=` plus your key, because the helper waits on a socket and the HTTP headers never reach it. The call resolves on confirmation and throws `TransactionExpiredBlockheightExceededError` once the height passes the deadline.

## Sending on Carbium

On Carbium a `sendTransaction` call costs 20 cells without preflight and 70 with it. If the loop sees no status after a few seconds and the deadline is still ahead, resending the same signed bytes is allowed: the signature stays the same, so the network keeps a single copy. Skipping preflight on those resends keeps them at the lower cost.

Polling is one way to wait. The other is a [WebSocket](https://carbium.sh/docs/websocket) `signatureSubscribe`, which sends one notification when the signature confirms and then ends on its own. `@solana/kit` builds its own send-and-confirm helper on subscriptions, with the key passed as `?api-key=` on the socket URL. A subscription costs credits to open by filter weight, and a signature subscription is in the lightest class at 5 credits. Polling suits a script that already holds an RPC client and wants no second connection. Keep the deadline check from this file in either design.

Limits are per [account](https://carbium.sh/docs/limits) and an account's keys share one budget, so several workers waiting on signatures draw from it even when each has its own key. Give each worker a poll interval that keeps the combined request rate under your plan.

## Where it ends

This file never sends. It proves the waiting logic against a real signature and a made-up one, and it signs nothing. The sending half, with a keypair and a built message, belongs in your own code, next to a retry policy. [Duplicate-safe retry check](https://carbium.sh/library/howsolana/duplicate-safe-retry-check) covers deciding whether a resend is safe.

The loop watches one endpoint for both reads. A second endpoint can sit behind the first, and its block height can lag. Keep the height and the status on the same URL, or an expired verdict can arrive from a node that has not yet seen the transaction.

A status found only at `processed` keeps the loop polling. That is deliberate, because a processed transaction can still lose its fork. The cost is that a signature stuck at processed with the deadline long gone never ends the loop. In production add your own ceiling, such as a maximum number of polls, and treat reaching it as unknown, then check the status once more before resending.

`getSignatureStatuses` here searches recent status only. An old signature, past what the node keeps, comes back as null, and the loop would report it as expired once the deadline passes. Use the loop for a signature you just sent, and use `getTransaction` for history. Remember `maxSupportedTransactionVersion: 1` on that call, or a v1 transaction answers -32015.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The loop never ends and the status stays null. | The deadline is far ahead of the chain's block height, most often because a slot number went in where `lastValidBlockHeight` belongs. Slots run about 22 million ahead of block height on mainnet. Pass the `lastValidBlockHeight` from `getLatestBlockhash`, compare it with a `getBlockHeight` read of your own, and add a maximum number of polls as a ceiling. |
| The loop reports expired and the transaction shows up on chain afterwards. | The status was read before the height. Read `getBlockHeight` first, then `getSignatureStatuses`, as the file does, and give a node that lags a poll or two before you rebuild. |
| A signature is reported as confirmed while the transaction failed. | Check `status.err` before the confirmation level. A failed transaction still reaches confirmed. The file returns failed first for that reason. |
| Send fails with a blockhash not found error before the loop starts. | The blockhash came from one read and the send went to a node that has not seen it. Fetch the blockhash at `confirmed` and send promptly, and pair it with the `lastValidBlockHeight` from the same response. |

## Questions

### What is the difference between this loop and a 30 second timeout?

A timeout ends on the clock, so the transaction may still land afterwards. The deadline ends on the chain's block height, which is the point after which the blockhash is invalid. Only the second tells you a rebuild cannot double-send.

### Where does lastValidBlockHeight come from?

It comes back with the blockhash in the `getLatestBlockhash` response. Use the pair from one response, and sign with exactly that blockhash.

### Do I need a WebSocket for this?

No. Polling `getSignatureStatuses` and `getBlockHeight` needs only the HTTP endpoint. A `signatureSubscribe` socket replaces the status poll, but you still compare block height against the deadline.

### Should I wait for finalized instead of confirmed?

Confirmed is enough for most screens. Wait for finalized when the result triggers something you cannot undo. Finalized trails confirmed by at most a slot or so now, so the extra wait is short.

## Related

- [Duplicate-safe retry check](https://carbium.sh/library/howsolana/duplicate-safe-retry-check) (How to use Solana, HS0093)
- [Withdrawal confirmation tracker](https://carbium.sh/library/usecase/withdrawal-confirmation-tracker) (Use cases, UC0063)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
