---
id: UC0087
title: "Escrow vault surplus check"
url: https://carbium.sh/library/usecase/escrow-vault-surplus-check
collection: Use cases
category: Payments and checkout
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Escrow vault surplus check

A read-only Node script that compares a vault's live token balance with the amount your deal expects, prints the surplus, and says whether a close would be refused. The on-chain pattern that avoids the failure is laid out beside it.

## Why close fails on a balance

A token account closes only at zero. The token program's close instruction checks the amount and fails with a non-zero balance error, whatever the calling program intended. Your escrow pays the seller, then closes the vault to return the rent, and the whole transaction reverts if one base unit is still sitting in it.

Anyone can put that unit there. A token transfer needs the sender's signature and the destination token account, and nothing from the destination's owner. The vault belongs to an address derived from your program, which has no key and no way to refuse a deposit. A stranger, a buyer who miscounted, or someone who wants your settlement stuck can each send one base unit, and a close written around the deal amount now reverts.

When the payout and the close sit in one instruction, the revert takes the payout with it. The seller is not paid, the rent stays locked, and the vault stays blocked until the program moves that unit out. A program with no path for that has a vault that nobody can empty.

## The safe pattern

The rule is that the program never assumes the balance equals the deal amount. It reads the balance at settlement, pays what the deal says is owed, and disposes of the rest before it closes. In one instruction that runs in this order:

- Reload the vault account after any earlier CPI, so the amount you read is the live one. In Anchor that is `reload()` on the token account. An amount stored at deposit time or computed off chain is a guess.
- Transfer the owed amount to the seller, or to the buyer on a refund, signed with the vault's PDA seeds.
- Transfer whatever remains to a destination the deal fixed when it was created, usually the depositor's token account or a treasury account. Fixing it at creation means nobody can steer the surplus at settlement.
- Reload again and require the amount to be zero.
- Close the vault, sending the rent to the account that paid for it.

Because all of this runs inside one transaction, no deposit can land between the steps. A deposit that arrives before the transaction runs is picked up by the first read, and one that arrives after the close finds no vault. An outside deposit only raises the balance, so the sweep moves whatever is there and the zero check after it holds.

A simpler variant transfers the entire live balance to the seller and closes. It is shorter and it works, but the windfall goes to the payee. An explicit owed amount with a separate sweep keeps partial releases and fee splits working.

## Surplus against obligation

Set the expected amount to what the deal still owes, which is below the original deposit after a partial release. The balance then lands in one of four cases.

| Balance against expected | What it means | What the instruction does |
|---|---|---|
| Equal | Nothing extra arrived | Pay the expected amount, close |
| Above | Someone credited the vault | Pay the expected amount, sweep the surplus to the fixed destination, close |
| Below, including a zero balance against a non-zero expected amount | Money the deal still owes is missing, for example a transfer out that the deal never authorized | Do not settle, and send the deal to its dispute path |
| Zero, with an expected amount of zero | The deal is already paid out in full | Skip the payout, close |

The third row is the one a surplus check must not confuse with the second. A shortfall means money that should be there is gone, and sweeping or closing it hides that. Raise an alarm and hold the settlement.

## Checking a vault from outside

The program has to do its own read, but an off-chain check still catches a vault before settlement day. It tells an operator that a stranger has credited a vault, so a settlement queue can show the surplus line before anyone submits the payout.

The script takes a vault token account and the expected amount in base units. It reads the balance with [getTokenAccountBalance](https://carbium.sh/docs/rpc) at `finalized`, because @solana/kit 8.6.0 fills in `confirmed` when a call leaves commitment out, and a settlement decision should rest on a balance that cannot move back. That one read costs 10 cells.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY node main.ts [vaultTokenAccount expectedBaseUnits]`)

```ts
// UC0087 · Escrow vault surplus check
// https://carbium.sh/library/usecase/escrow-vault-surplus-check
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only, one shot: an escrow vault's live token balance against the amount the deal expects.
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";

const apiKey = process.env.CARBIUM_KEY;
if (!apiKey) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1); }
const endpoint = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const chain = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: endpoint, headers: { "x-api-key": apiKey } }));

type Held = { accountIndex: number; mint: string; uiTokenAmount: { amount: string } };
type ParsedTx = { transaction: { message: { accountKeys: { pubkey: string }[] } }; meta: { preTokenBalances?: Held[] | null } | null };

// Close verdict for a vault: the printed lines for balance, surplus, the close rule and the plan.
function closeVerdict(vault: string, expected: bigint, live: bigint): string[] {
  const surplus = live - expected;
  const plan = surplus > 0n ? `plan: pay ${expected}, sweep ${surplus} to the destination fixed at creation, reload, close`
    : surplus < 0n ? `plan: vault is short by ${-surplus}, do not settle`
    : "plan: pay the expected amount, then close";
  const close = surplus > 0n ? `close: REFUSED until the ${surplus} surplus is swept`
    : surplus < 0n ? "close: do not settle, the vault is short"
    : "close: allowed once the expected amount is paid, nothing is left";
  return [`vault    ${vault}`, `expected ${expected}`, `actual   ${live}`, `surplus  ${surplus}`, close, plan];
}

// Stand-in when no arguments are given: a USDC token account from the mint's newest transactions, its pre-balance as the expected amount.
async function standIn(): Promise<[string, string] | undefined> {
  try {
    const recent = await chain.getSignaturesForAddress(address(USDC_MINT), { limit: 5, commitment: "finalized" }).send();
    for (const item of recent) {
      if (item.err !== null) continue;
      // Mainnet carries v1 transactions: a maxSupportedTransactionVersion of 0 or none gets -32015 for one.
      const tx = (await chain.getTransaction(signature(item.signature), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" }).send()) as unknown as ParsedTx | null;
      const held = tx?.meta?.preTokenBalances?.find((b) => b.mint === USDC_MINT && BigInt(b.uiTokenAmount.amount) > 0n);
      const account = held ? tx?.transaction.message.accountKeys[held.accountIndex]?.pubkey : undefined;
      if (held && account) return [account, held.uiTokenAmount.amount];
    }
  } catch (e) { console.error(`stand-in lookup failed: ${e}`); }
  return undefined;
}

const [argVault, argExpected] = [process.argv[2], process.argv[3]];
const usage = "Usage: node main.ts [vaultTokenAccount expectedBaseUnits]";
if (argVault && argExpected === undefined) { console.error(usage); process.exit(1); }
const target = argVault && argExpected !== undefined ? [argVault, argExpected] as [string, string] : await standIn();
if (!target) { console.error(`Pass a vault token account and the expected amount in base units. ${usage}`); process.exit(1); }

let expected: bigint;
try { expected = BigInt(target[1]); } catch { console.error(`The expected amount must be whole base units, got "${target[1]}".`); process.exit(1); }

let live: bigint;
try {
  live = BigInt((await chain.getTokenAccountBalance(address(target[0]), { commitment: "finalized" }).send()).value.amount);
} catch (e) { console.error(`balance read failed (a closed vault has no balance): ${e}`); process.exit(1); }

for (const line of closeVerdict(target[0], expected, live)) console.log(line);
```

With no arguments the script finds a stand-in. It lists the newest transactions that mention the USDC mint, reads each with `maxSupportedTransactionVersion: 1` because mainnet carries v1 transactions and Carbium answers -32015 for one when the value is absent or 0, and takes the first token account that held USDC before the transaction. That account's pre-balance becomes the expected amount, so any movement since that transaction shows up as a surplus or a shortfall with the matching plan line. The page of signatures costs 50 cells and each transaction costs 50. The script is a one-shot read you run before a close. Watching a vault over time is your own scheduler's job.

For a real vault, run it from the job that prepares the settlement and alert on a positive surplus. The related reads for closed vaults are in [Closed account detection](https://carbium.sh/library/howsolana/closed-account-detection), and the same balance read in more detail is in [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).

## Where it ends

- Carbium serves the reads. The fix itself lives in your program, and the script signs and sends nothing.
- An off-chain balance is a snapshot. Another deposit can land between your read and the settlement, which is why the instruction reads the balance itself.
- A Token-2022 mint with the transfer fee extension holds withheld fees inside token accounts, and a non-zero withheld amount also blocks a close. HarvestWithheldTokensToMint is permissionless, so the program, or anyone, can harvest the withheld fees from the vault to the mint in the same settlement before the close. Only WithdrawWithheldTokensFromAccounts needs the mint's withdraw authority. The script does not show the withheld amount. Fee maths is in [Transfer fee calculator](https://carbium.sh/library/howsolana/transfer-fee-calculator).
- Where the surplus goes is a policy of your deal. The script reports the number and leaves the destination to the program.
- The script reads the one token account you pass. A wallet can own more than one token account for a mint, so pass the vault's token account address.
- A closed vault has no balance to read, and the script reports the failed read. How to tell a closed vault from an outage is in [Escrow release monitor](https://carbium.sh/library/usecase/escrow-release-monitor).

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Close reverts with a non-zero balance error right after a correct payout. | Something credited the vault after the deal was funded. Sweep the live remainder to the fixed destination before the close, and require zero after a reload. |
| The payout compares the vault balance with the deal amount and aborts on a mismatch. | An equality check lets any stranger block settlement with one base unit. Pay the owed amount and treat only a balance below it as an error. |
| The sweep amount is wrong because the vault account data is stale after the payout transfer. | Reload the token account after each CPI that moves tokens, then read the amount. |
| A close still fails on a Token-2022 vault with a zero balance. | Withheld transfer fees in the account block the close. Harvest them to the mint with a CPI to the permissionless HarvestWithheldTokensToMint, then close. |
| The stand-in lookup fails with -32015 on a recent USDC transaction. | Pass `maxSupportedTransactionVersion: 1` on getTransaction. With the value absent or 0, Carbium answers -32015 for a v1 transaction. |

## Questions

### Can I stop strangers from sending tokens to my vault?

No. The token program lets anyone credit any token account, and a program-owned vault cannot decline. Design the settlement so a surplus is routine.

### Should the surplus go to the seller?

That is a deal policy. Most escrows return it to the depositor or a treasury so the payee receives exactly the agreed amount. Whichever you pick, fix it at creation.

### Why not require the balance to equal the deal amount before paying?

Because it hands control of your settlement to whoever sends the extra unit. The check belongs on the shortfall side only.

### What does one check cost on Carbium?

With a vault and an amount passed in, one balance read, which is 10 cells. The stand-in adds a 50-cell signature page and up to five 50-cell transaction reads.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Escrow release monitor](https://carbium.sh/library/usecase/escrow-release-monitor) (Use cases, UC0056)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
