services
Get a key

library / AI and blockchain / SI0028

Pre-sign transaction guard

You get a read-only script that decodes an unsigned transaction and prints PASS or BLOCK with a reason per finding. It checks the payer, programs, SOL transfer size, token approvals, fee and program accounts, so an agent asks it before any key signs.

By Carbium · Agent wallets and signing safety · SI0028 · updated 2026-11-22

01

What to check before signing

An agent that builds a transaction and signs it in the same step has no point where anything can say no. The guard is that point. It takes the unsigned bytes, decodes the message the way a validator will read it, and answers PASS or BLOCK with one line per finding. No key is involved at any stage, and the guard cannot send anything.

Most of what a harmful transaction does is visible in the message itself. Five checks run on the bytes alone.

  • The fee payer is the wallet the agent was told to act for, and the message asks for no other signature. A second required signer means some other key is expected to authorise part of the transaction.
  • Every instruction runs in a program on a short allowlist: system, the two token programs, associated token account, memo and compute budget. A swap venue joins the list after a person has looked at it.
  • System transfers stay under a lamport ceiling, and token instructions that hand out control are refused: Approve, ApproveChecked, SetAuthority and CloseAccount. The first three move no tokens in that instruction. They change who may move the tokens later, which is why an amount check never catches them. CloseAccount closes the account and sends its lamports to a destination, and for a wrapped SOL account that destination receives the balance.
  • Every system instruction other than Transfer is blocked. Assign or CreateAccountWithSeed signed by the payer would otherwise pass the allowlist, because the system program is on it, and could hand the wallet or its lamports to a program that is not.
  • The message carries no address lookup table. A table hides account addresses behind an index, so the file blocks the message instead of guessing what sits behind it.

Any one finding blocks, and a read that fails counts as a finding. Two further checks ask the chain.

02

The guard file

One file, on @solana/kit and Node's own modules. Node 24 strips the types and runs it. Set CARBIUM_KEY first; the file exits with a message when it is missing. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh.

main.ts
// SI0028 · Pre-sign transaction guard// https://carbium.sh/library/si/pre-sign-transaction-guard// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Pre-sign transaction guard. Run: CARBIUM_KEY=... node main.ts [base64 unsigned transaction]import {  AccountRole, address, appendTransactionMessageInstructions, compileTransaction, createDefaultRpcTransport,  createSolanaRpcFromTransport, createTransactionMessage, getBase64Decoder, getBase64EncodedWireTransaction,  getBase64Encoder, getCompiledTransactionMessageDecoder, getTransactionDecoder, pipe,  setTransactionMessageFeePayer, setTransactionMessageLifetimeUsingBlockhash,} 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 } }));// The wallet the agent acts for. The default is a stand-in for the two demo messages.const PAYER = address(process.env.GUARD_WALLET ?? "So11111111111111111111111111111111111111112");const DEST = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");const SYSTEM = "11111111111111111111111111111111";const TOKEN = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";// System, token, token-2022, associated token account, memo and compute budget programs.const ALLOWED = new Set([SYSTEM, TOKEN, "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",  "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr",  "ComputeBudget111111111111111111111111111111"]);const CONTROL: Record<number, string> = { 4: "Approve", 6: "SetAuthority", 9: "CloseAccount", 13: "ApproveChecked" };const MAX_TRANSFER = BigInt(1_000_000_000); // lamportsconst MAX_FEE = BigInt(100_000); // lamportsasync function guard(label: string, wire: string) {  const tx = getTransactionDecoder().decode(getBase64Encoder().encode(wire));  const msg: any = getCompiledTransactionMessageDecoder().decode(tx.messageBytes);  const keys: string[] = msg.staticAccounts;  const found: string[] = [];  if (keys[0] !== PAYER) found.push(`fee payer is ${keys[0]}`);  if (msg.header.numSignerAccounts !== 1) found.push(`${msg.header.numSignerAccounts} signatures requested`);  if (msg.addressTableLookups?.length) found.push("address lookup tables hide accounts");  for (const ix of msg.instructions) {    const program = keys[ix.programAddressIndex];    const data: Uint8Array = ix.data ?? new Uint8Array();    if (!ALLOWED.has(program)) found.push(`program ${program} is not allowed`);    if (program === SYSTEM) {      // Only Transfer (discriminator 2, a little-endian u32) passes; Assign, CreateAccountWithSeed and the rest block.      if (data[0] !== 2 || data[1] || data[2] || data[3]) found.push(`system instruction ${data[0]} is not a transfer`);      else {        const lamports = data.slice(4, 12).reduceRight((n, b) => n * BigInt(256) + BigInt(b), BigInt(0));        if (lamports > MAX_TRANSFER) found.push(`transfer of ${lamports} lamports is over the ceiling`);      }    }    if (program.startsWith("Token") && CONTROL[data[0]]) found.push(`token ${CONTROL[data[0]]}`);  }  const programs = [...new Set<string>(msg.instructions.map((ix: any) => keys[ix.programAddressIndex]))];  const [fee, accounts] = await Promise.allSettled([    rpc.getFeeForMessage(getBase64Decoder().decode(tx.messageBytes) as any).send(),    rpc.getMultipleAccounts(programs.map((p) => address(p)), { encoding: "base64" }).send(),  ]);  if (fee.status === "rejected") found.push(`fee read failed: ${fee.reason}`);  else if (fee.value.value === null) found.push("fee unknown, the blockhash is no longer known");  else if (fee.value.value > MAX_FEE) found.push(`fee ${fee.value.value} lamports is over the ceiling`);  if (accounts.status === "rejected") found.push(`program read failed: ${accounts.reason}`);  else accounts.value.value.forEach((a, i) => a?.executable || found.push(`${programs[i]} is missing or not executable`));  console.log(`${label}: ${found.length ? "BLOCK" : "PASS"}`);  for (const f of found) console.log(`  ${f}`);}const transfer = (lamports: bigint) => {  const data = new Uint8Array(12);  data[0] = 2;  for (let i = 0, n = lamports; i < 8; i++, n /= BigInt(256)) data[4 + i] = Number(n % BigInt(256));  return { programAddress: address(SYSTEM), data, accounts: [    { address: PAYER, role: AccountRole.WRITABLE_SIGNER }, { address: DEST, role: AccountRole.WRITABLE }] };};const setAuthority = { programAddress: address(TOKEN), data: Uint8Array.from([6, 2, 1, ...new Uint8Array(32)]),  accounts: [{ address: DEST, role: AccountRole.WRITABLE }, { address: PAYER, role: AccountRole.READONLY_SIGNER }] };const unlisted = { programAddress: address("Vote111111111111111111111111111111111111111") };const build = (instructions: any[], blockhash: any) => getBase64EncodedWireTransaction(compileTransaction(pipe(  createTransactionMessage({ version: 0 }),  (m) => setTransactionMessageFeePayer(PAYER, m),  (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m),  (m) => appendTransactionMessageInstructions(instructions, m),)));const cases: [string, string][] = [];if (process.argv[2]) cases.push(["given transaction", process.argv[2]]);else {  const { value } = await rpc.getLatestBlockhash().send();  cases.push(["small transfer", build([transfer(BigInt(1_000_000))], value)]);  cases.push(["risky message", build([transfer(BigInt(5_000_000_000)), setAuthority, unlisted], value)]);}for (const [label, wire] of cases) {  try {    await guard(label, wire);  } catch (e) {    console.log(`${label}: BLOCK\n  unreadable: ${(e as Error).message}`);  }}

run: node main.ts

Pass the base64 of a full unsigned transaction and it guards that one. With no argument it builds two transactions of its own and guards both, so you can see each verdict: a small transfer, and a message that moves 5 SOL, calls an unlisted program and changes a token account's authority. Building them only compiles bytes. Nothing is signed. Set GUARD_WALLET to the address the agent acts for; the default is a stand-in used by the two demo messages.

Output lineMeaning
<label>: PASSevery check cleared
<label>: BLOCKat least one finding follows, one line each
fee payer is <address>the first account differs from GUARD_WALLET
program <address> is not allowedan instruction runs outside the allowlist
system instruction <n> is not a transfera system instruction other than Transfer
token SetAuthoritya token instruction that changes who controls an account
unreadable: <message>the decoder could not read the input, so it is blocked

The ceilings are two constants at the top, MAX_TRANSFER in lamports and MAX_FEE in lamports. Both are policy, so keep them in configuration the model cannot write to.

03

The two reads from the chain

getFeeForMessage takes the compiled message in base64 and returns the fee in lamports. It answers null when the node no longer knows the blockhash, so a null means the transaction would be dropped on send, and the guard blocks it with that reason. A fee above MAX_FEE blocks too, which catches a compute unit price an agent set far too high. For choosing that price in the first place, see Priority fee per compute unit.

getMultipleAccounts reads the distinct program ids in one call and confirms each exists and is executable. A mistyped program address, or one that no longer exists, shows up here and nowhere else in the message. It charges 10 cells per pubkey, so a message with four programs costs 40 cells, and below Pro a call takes at most 100 pubkeys because of the 1,024-cell burst. A transaction never has that many distinct programs.

CallWhat it settles
getLatestBlockhasha fresh lifetime for the two demo messages only
getFeeForMessagefee in range and blockhash still known
getMultipleAccountseach program exists and is executable

The three calls leave commitment out, so @solana/kit fills in confirmed, where the JSON-RPC server alone would use finalized. The two reads run together with Promise.allSettled. If one rejects, for example on a 429, the file prints the error and records a finding.

04

Placing it in an agent loop

The guard sits between the tool that builds and the process that signs. The build tool returns base64 and nothing else. The guard runs on that exact string. Only a PASS on the same bytes reaches the signer, so a model cannot alter the message after the check, and the signer never receives a transaction the guard has not seen.

A swap built with the swap method on the RPC endpoint comes back as one unsigned transaction that your software signs and sends through any RPC. A swap transaction that uses address lookup tables always blocks under this guard until the guard resolves the tables. The quote's platformFee is 5 bps and is charged on chain inside that transaction, so expect it as a movement of value you did not add yourself. The venue programs a route uses must be on the allowlist before the guard lets it through. Add them after reading what each program does, and keep the list in a file the model has no write path to. For checking the outcome of a swap you sent, see Swap transaction decoder.

Hand the reason lines back to the model. A BLOCK for an oversized transfer or an unlisted program is something the agent can repair by rebuilding, and a line such as fee payer is X tells it exactly which field was wrong. Do not hand it the ability to change a ceiling or the allowlist.

After a PASS and a signature, sendTransaction costs 20 cells without preflight and 70 with it. Preflight runs a simulation the guard does not run, so keep it on and expect the 70-cell price.

05

Where it ends

  • The file reads what instructions ask for. It runs no simulation, so it does not see the balance changes the transaction would cause, and a program on the allowlist can still do more than its name suggests.
  • Address lookup tables are blocked outright. Handling them means reading each table account and resolving the indexes, which this file does not do.
  • Only the system program's transfer instruction is amount-checked, and every other system instruction is blocked. Token transfers and any swap venue program need their own parsing before their amounts mean anything to the guard.
  • It does not check recipients. Add a recipient allowlist by reading the destination account index of each instruction if the agent only ever pays known addresses.
  • A PASS says the message matches the policy. It says nothing about whether the policy is right, or about a key that signs something other than the bytes that were guarded.
06

When it goes wrong

what goes wrongwhat to do
Every run blocks with fee payer is <address>.GUARD_WALLET is unset, so the file compares against its demo stand-in. Set it to the address of the wallet the agent acts for.
The fee read returns null and the message blocks.The node no longer knows the blockhash, so the transaction would not land. Build it again with a fresh blockhash and guard the new bytes.
A program prints as missing or not executable.The instruction names an address that holds no program, often a typo or a closed program. Do not sign. Compare the address with the one in your venue configuration.
A 429 on getFeeForMessage or getMultipleAccounts in a busy loop.The failed read already blocked the message, which is the right outcome. Build the transaction and guard it again once the limit clears.
unreadable on input that is a valid transaction.The decoder expects base64 of the whole wire transaction, with its signature slots. A bare message, or a base58 string, fails. Encode the full transaction bytes as base64.
401 from the RPC at the first read.The key is unknown at the door. Attach the whole key in the x-api-key header, with nothing cut off.
07

Questions

Does the guard simulate the transaction?

No. It reads the instructions and two account facts, which need no execution. A simulation would add the balance changes, and you can run one separately and pass both before signing.

Why does a failed read block the message?

A guard that passes when it could not check has lost its purpose. A rejected fee or account read adds a finding, so a slow or rate-limited call stops the transaction and the caller retries.

How do I allow one swap venue?

Add its program id to the ALLOWED set after reading what the program does. Keep that set in configuration the agent cannot edit, and rerun the guard on a real built swap to see what else it prints.

How many reads does one guard run cost?

One getFeeForMessage and one getMultipleAccounts, which charges 10 cells per distinct program. A message with four programs costs 40 cells for the second call. getMultipleAccounts runs at 0.5, 15, 50 and 400 req/s on Free, Dev, Business and Pro.