library / How to use Solana / HS0061
Versioned transaction round-trip
One TypeScript file fetches three finalized transactions as base64, decodes each with @solana/kit, encodes it again and compares the bytes. It prints version, signature count, accounts, lookups and size. It only reads.
What the bytes hold
A serialized transaction is two parts in a row. The first is a signature count followed by that many 64-byte signatures. The second is the message. Each signature is made over the message bytes exactly as they sit on the wire, so every field of the message is part of what was signed, down to the order of the accounts.
The first byte of the message carries the version. A legacy message opens with its header, whose first byte is the number of required signatures and stays below 128. A version 0 message opens with a prefix byte whose top bit is set and whose low bits hold the version, so 0x80 for version 0. Then come three header bytes, the static account keys at 32 bytes each, the recent blockhash, the instructions, and for version 0 a list of address table lookups. A lookup names a table and gives two lists of indexes into it, one for writable accounts and one for read-only ones. A legacy or version 0 transaction is capped at 1,232 bytes as a whole packet.
| Part | Holds | Size |
|---|---|---|
| Signatures | One slot per required signer, zero filled until signed | 64 bytes each |
| Message prefix | Version, version 0 only | 1 byte |
| Header and static accounts | Signer and read-only counts, then the account keys | 3 bytes, then 32 bytes per key |
| Blockhash and instructions | The lifetime and the calls, as account indexes | Varies |
| Lookups | Table address plus writable and read-only indexes, version 0 only | 32 bytes plus the indexes |
An unsigned transaction keeps its signature slots at full size. The swap method hands back exactly that, an unsigned transaction, and passing it between services is the same round trip as passing a landed one.
Decoding with kit
@solana/kit splits the work in two. getTransactionDecoder reads the outer envelope and returns an object with messageBytes and signatures. The signatures are a map from each signer's address to its signature, or to null for a signer that has not signed yet.
getCompiledTransactionMessageDecoder reads messageBytes and returns the compiled message: version, header, staticAccounts, the lifetime token, the instructions and, for version 0, addressTableLookups. Compiled means the instructions still hold account indexes. Turning an index into an address is a later step, and for a lookup table account it needs the table's contents.
getTransactionEncoder runs the first decoder backwards. Give it the object the decoder returned and it writes the same envelope. The object keeps messageBytes as raw bytes and never rebuilds the message, so nothing can drift on the way out.
The code
Export CARBIUM_KEY, install @solana/kit at 8.6.0 and give the file an address with fresh traffic, such as a busy program. It lists the newest signatures at finalized commitment, keeps three that succeeded and fetches them in parallel with encoding: "base64" and maxSupportedTransactionVersion: 1. Each fetch is settled on its own with Promise.allSettled, so one failure prints a line and the other two still finish.
// HS0061 · Versioned transaction round-trip// https://carbium.sh/library/howsolana/versioned-transaction-round-trip// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getCompiledTransactionMessageDecoder, getTransactionDecoder, getTransactionEncoder, 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 [addr] = process.argv.slice(2);if (!addr) { console.error("Usage: node main.ts <address with recent transactions>"); process.exit(1);}type Compiled = { version: unknown; staticAccounts: readonly unknown[]; addressTableLookups?: readonly unknown[];};async function roundTrip(signature: Signature): Promise<string> { const tx = await rpc .getTransaction(signature, { commitment: "finalized", encoding: "base64", maxSupportedTransactionVersion: 1, }) .send(); const label = signature.slice(0, 8); if (!tx) return `${label}: null, no body served`; const wire = Buffer.from(tx.transaction[0], "base64"); const decoded = getTransactionDecoder().decode(wire); const message = getCompiledTransactionMessageDecoder().decode( decoded.messageBytes, ) as unknown as Compiled; const again = Buffer.from(getTransactionEncoder().encode(decoded)); const rpcVersion = String((tx as { version?: unknown }).version); return [ `${label}: version ${String(message.version)} (rpc says ${rpcVersion})`, `signatures ${Object.keys(decoded.signatures).length}`, `static accounts ${message.staticAccounts.length}`, `lookups ${message.addressTableLookups?.length ?? 0}`, `bytes ${wire.length}`, again.equals(wire) ? "identical" : "differs", ].join(", ");}const sigs = await rpc .getSignaturesForAddress(address(addr), { commitment: "finalized", limit: 10 }) .send();const picked = sigs.filter((s) => s.err === null).slice(0, 3);if (picked.length === 0) console.log("No successful signatures found; try a busier address.");const results = await Promise.allSettled(picked.map((s) => roundTrip(s.signature)));results.forEach((r, i) => { if (r.status === "fulfilled") console.log(r.value); else console.log(`${picked[i]?.signature.slice(0, 8)}: failed, ${String(r.reason)}`);});
run: node main.ts <busy-program-address>
A base64 answer arrives as a two-item array, the string and the word base64, so tx.transaction[0] is the text to decode. Both calls pass commitment: "finalized", because kit fills in confirmed when a call leaves it out. The version comes from two places on purpose: the compiled message and the version field of the answer. They should match.
getTransaction and getSignaturesForAddress cost 50 cells each, so one run of three transactions is four calls and 200 cells. Both allow 0.24 req/s on Free, and the 200 cells of one run fit inside the 1,024-cell burst.
Where round trips break
- Base58 against base64. The same bytes written in the two alphabets are two unrelated strings. Base64 text read as base58 fails or produces other bytes, and the decoder then complains about a length or a version that was never there. Ship the encoding name beside the string and use base64 in both directions.
- Recompiling a message. Decode, rebuild the message with a builder and compile it again, and the compiler sorts accounts by role in its own order, which can differ from the order the author used. The new messageBytes differ, the old signatures no longer verify, and the network rejects the transaction. Keep the original messageBytes unless you mean to sign again.
- Lookup tables unresolved. A version 0 message holds table addresses and indexes only. Decompiling it into instructions with real addresses needs each table's contents as they were when the transaction was built. A landed transaction carries them in the loadedAddresses field of meta, and a pending one needs the table accounts read first.
- Expired lifetime. A byte-identical transaction is still bound to its blockhash. Passing it between services faster does not extend how long that blockhash stays valid.
Where it ends
Identical bytes prove the codec and nothing else. The file does not verify signatures, check the blockhash or simulate anything. A transaction that round-trips can still be one the network refuses.
Mainnet carries version 1 transactions as well, and their messages use a layout different from the table in the first section. @solana/kit 8.6.0 decodes them, and the round trip comes back identical.
Signature listing reaches back 30 days at most, and its pages reach below the validator's ledger floor. getTransaction can therefore answer null for an older signature the listing returned. The file prints a line for null and moves on, and the newest signatures are the ones to prove it with.
The file never signs, sends or holds a key pair. Signing is a separate step that works on the same messageBytes, and a signer should receive the message bytes untouched.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Error -32015 from getTransaction or getBlock, with a version in the message. | Add maxSupportedTransactionVersion: 1 next to the encoding in the config object. A value of 0 still refuses version 1. |
| The decoder throws on a string that looks like a transaction, or the decoded version byte makes no sense. | The text is in a different encoding from the one you decoded. Base58 and base64 do not mix. Decode with the encoding the sender named, and ask for base64. |
| Signatures fail after the transaction was decoded and compiled again. | Recompiling can reorder accounts, so the message bytes changed. Pass the original messageBytes through and sign again only when you must change the message. |
| getTransaction answers null for a signature the listing returned. | Older entries can fall below the ledger floor. Take the newest signatures, or retry that signature later if it is only moments old. |
| Accounts in a version 0 message look wrong or too few. | You read instruction indexes against staticAccounts alone. Add the table contents, writable first and then read-only, or use loadedAddresses from meta on a landed transaction. |
Questions
Do I need to decode a transaction just to forward it?
No. Keep the base64 string and its encoding name together and pass them on as text. Decode only where you need to read the content.
Does the version byte change how I encode?
Version 1 changes the envelope: the message comes first and the signatures follow it, with no count in front. The kit decoder and encoder read the version from the bytes and pick the layout, so you never set the version yourself when you pass bytes through.
Why does the file print the version twice?
One value comes from the compiled message and one from the version field of the RPC answer. A mismatch would show that the bytes and the answer describe different transactions.
Can I decode a transaction from the swap method the same way?
Yes, in whatever encoding it arrives. Its signature slots are empty until the wallet signs, and the round trip leaves them empty.