---
id: UC0056
title: "Escrow release monitor"
url: https://carbium.sh/library/usecase/escrow-release-monitor
collection: Use cases
category: Stablecoin treasury and B2B settlement
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Escrow release monitor

A read-only Node script that reports an escrow vault's balance and each outflow with its destination owner, then calls the outcome released, refunded or held. Notifications from the vault can trigger the same reads, and the escrow program's own state settles any dispute.

## An escrow is a token account

On Solana an escrow is rarely a wallet that someone holds a key for. A program creates a token account for the deal and sets its owner to an address derived from the program, so no private key exists for it. The buyer's deposit lands in that account, and only the program can sign for it. The program signs when its own rules call for a release or a refund.

That makes the vault's history the deal's history: a deposit in, then one or more transfers out. A monitor needs no knowledge of the program's instruction layout. It reads the vault's token balance and, for each transaction that touched the vault, which token accounts gained what the vault lost. The amounts and destinations are the outcome, whichever program, version or router moved the money.

## Three outcomes and how each reads

| Outcome | What the vault shows | Where the amount went |
|---|---|---|
| Held | Balance equals the deposit, no transaction took tokens out | Nowhere yet |
| Released | Balance fell by the released amount | A token account owned by the seller |
| Refunded | Balance fell by the refunded amount | A token account owned by the buyer |

Real deals add shapes to this table. A release can split between the seller and a fee wallet, so one transaction has two destinations. A partial release leaves a balance and a later transaction empties it. After the last transfer the program may close the vault, and then the balance read fails, which is covered in [Closed account detection](https://carbium.sh/library/howsolana/closed-account-detection).

The destination matters more than the amount. A release and a refund can move the same number of base units, and only the owner of the receiving token account tells them apart.

## Watching the vault

Poll with three reads. `getTokenAccountBalance` gives the current amount, `getSignaturesForAddress` on the vault lists its recent transactions, and `getTransaction` shows what each one moved. Carbium builds those signature pages from its own [address index](https://carbium.sh/docs#migrate), which keeps up to 30 days. An empty page past that is the index's age limit, so a long escrow needs your own record of the signatures you have already classified.

| Method | Cells per call | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|
| getSignaturesForAddress | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | 50 | 0.24 | 1.2 | 5 | 25 |
| getTokenAccountBalance | 10 | 0.5 | 15 | 50 | 400 |

A vault changes only when a deal moves, so polling every few seconds across many vaults spends cells for nothing. Push the work to the [WebSocket](https://carbium.sh/docs#websocket) instead. `accountSubscribe` sends the account's state when it changes, and `logsSubscribe` with a mention filter streams each transaction that names the vault. Treat a notification as a prompt and run the same three reads, so one code path decides the outcome. A subscription of that weight opens at 25 credits and then costs 20 credits per MiB sent. The field layout of a notification is in [Account notification fields](https://carbium.sh/library/howsolana/account-notification-fields).

## Classifying the destination

The script takes a vault token account, then optionally the buyer's wallet and the seller's wallet. For each of the vault's last five successful transactions it calls [getTransaction](https://carbium.sh/docs#rpc) in `jsonParsed` encoding with `maxSupportedTransactionVersion: 1`, because mainnet carries v1 transactions and Carbium answers -32015 for one when the value is absent or 0. Every call sets `finalized`, since @solana/kit 8.6.0 fills in `confirmed` when commitment is left out and a release should be read at the level where it can no longer move.

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

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

// Read-only: an escrow vault's balance and where each outflow went, sorted against the buyer and seller wallets.
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, 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 [vaultArg, buyer, seller] = process.argv.slice(2);
const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));

type Bal = { accountIndex: number; mint: string; owner?: string; uiTokenAmount: { amount: string } };
type Tx = { transaction: { message: { accountKeys: { pubkey: string }[] } }; meta: { err: unknown; preTokenBalances?: Bal[] | null; postTokenBalances?: Bal[] | null } | null };

// Mainnet carries v1 transactions: a maxSupportedTransactionVersion of 0 or none gets -32015 for one.
const getTx = async (sig: string) =>
  (await rpc.getTransaction(signature(sig), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" }).send()) as unknown as Tx | null;

// Token-account deltas for the vault's mint: the vault's own change and every account that gained.
function read(tx: Tx, vault: string) {
  const m = tx.meta, keys = tx.transaction.message.accountKeys.map((k) => k.pubkey);
  const i = keys.indexOf(vault);
  if (!m || m.err || i < 0) return null;
  const mint = [...(m.preTokenBalances ?? []), ...(m.postTokenBalances ?? [])].find((b) => b.accountIndex === i)?.mint;
  const delta = new Map<number, bigint>(), owner = new Map<number, string>();
  for (const [list, sign] of [[m.preTokenBalances, -1n], [m.postTokenBalances, 1n]] as const)
    for (const b of list ?? []) {
      if (b.mint !== mint) continue;
      delta.set(b.accountIndex, (delta.get(b.accountIndex) ?? 0n) + sign * BigInt(b.uiTokenAmount.amount));
      if (b.owner) owner.set(b.accountIndex, b.owner); // the receiving wallet is only in the token balances
    }
  const to = [...delta].filter(([j, d]) => j !== i && d > 0n).map(([j, d]) => ({ account: keys[j], owner: owner.get(j), amount: d }));
  return { vaultDelta: delta.get(i) ?? 0n, to };
}

// With no argument: a token account that just lost USDC in one of the mint's newest transactions.
async function standIn(): Promise<string | undefined> {
  const page = await rpc.getSignaturesForAddress(address(USDC), { limit: 5, commitment: "finalized" }).send();
  for (const s of page.filter((p) => p.err === null)) {
    const tx = await getTx(s.signature);
    const m = tx?.meta;
    if (!tx || !m) continue;
    const lost = (m.postTokenBalances ?? []).find((p) => p.mint === USDC &&
      BigInt(p.uiTokenAmount.amount) < BigInt((m.preTokenBalances ?? []).find((q) => q.accountIndex === p.accountIndex)?.uiTokenAmount.amount ?? "0"));
    if (lost) return tx.transaction.message.accountKeys[lost.accountIndex]?.pubkey;
  }
}

const vault = vaultArg ?? (await standIn());
if (!vault) { console.error("No vault given and no USDC outflow found in the newest transactions."); process.exit(1); }
console.log(`vault ${vault}`);

const [bal, sigs] = await Promise.allSettled([
  rpc.getTokenAccountBalance(address(vault), { commitment: "finalized" }).send(),
  rpc.getSignaturesForAddress(address(vault), { limit: 10, commitment: "finalized" }).send(),
]);
console.log(bal.status === "fulfilled" ? `balance ${bal.value.value.amount} base units` : `balance read failed: ${bal.reason}`);
if (sigs.status === "rejected") { console.error(`signature page failed: ${sigs.reason}`); process.exit(1); }

const ids = sigs.value.filter((s) => s.err === null).slice(0, 5).map((s) => s.signature);
const txs = await Promise.allSettled(ids.map(getTx));
let released = false, refunded = false, other = false;
txs.forEach((r, n) => {
  const id = `${ids[n]?.slice(0, 12)}...`;
  if (r.status === "rejected") return console.log(`${id} read failed: ${r.reason}`);
  const x = r.value && read(r.value, vault);
  if (!x) return console.log(`${id} not returned or does not touch the vault`);
  if (x.vaultDelta >= 0n) return console.log(`${id} deposit ${x.vaultDelta}`);
  for (const d of x.to) {
    const o = d.owner;
    const kind = o && o === seller ? "release to seller" : o && o === buyer ? "refund to buyer" : "outflow to another owner";
    if (o && o === seller) released = true; else if (o && o === buyer) refunded = true; else other = true;
    console.log(`${id} ${kind}: ${d.amount} to token account ${d.account}, owner ${o ?? "unknown"}`);
  }
});
console.log(`status: ${released ? "RELEASED" : refunded ? "REFUNDED" : other ? "OUTFLOW seen, pass buyer and seller to classify" : "HELD, no outflow in the last transactions"}`);
```

A token transfer into an existing token account lists the two token accounts and the sender's authority. It never lists the receiving wallet. So the script reads the destination owner from the `owner` field of the post token balances and uses the account keys only to find the vault's position. That is why a refund to the buyer's wallet shows up under the buyer even when the buyer's address is absent from the transaction's key list.

With no argument the script picks a stand-in. It lists the newest transactions that mention the USDC mint, finds one where a token account lost USDC, and monitors that account. Pass your own vault, buyer and seller to get the three-way verdict. Without them every destination prints as another owner, with its address, and the status line says an outflow was seen.

## Where it ends

- Carbium serves the reads. It does not run an escrow, hold funds or sign for a vault, and the script moves nothing.
- The script shows what left the vault and who received it. Whether the release was right under the contract's terms is decided by the escrow program, and a dispute outcome lives in its state and instructions.
- Five transactions cover a simple deal. A vault with a long history needs your own ledger of classified signatures and a page through `getSignaturesForAddress` past the first five.
- Mapping a wallet address to a buyer or a seller is your records' job. The script only compares against the two addresses you pass.
- getTransaction can answer null for a signature the page lists, because the signature index reaches below the validator's ledger floor. The script prints that and moves on.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The refund is booked as a release because the destination is read from the account keys. | Read the owner from the post token balances. A transfer to an existing token account lists token accounts and the sender's authority, never the receiving wallet. |
| getTransaction fails with -32015 on a vault transaction. | Pass `maxSupportedTransactionVersion: 1` on every getTransaction call. With the value absent or 0, Carbium answers -32015 for a v1 transaction. |
| A release is read at confirmed because a call left commitment out. | Set `commitment: "finalized"` on the balance, the signature page and each transaction. Kit fills in confirmed otherwise. |
| The balance read errors and the deal is taken as lost. | The program may have closed the vault after its last transfer. Classify from the transaction history, and treat a closed account as the end of the deal. |
| An old escrow shows no transactions and looks untouched. | The address index keeps up to 30 days, and an empty page past that is its age limit. Keep the signatures you classified in your own store. |

## Questions

### How do I tell a release from a refund?

By the owner of the token account that received the outflow. Compare it with the seller and buyer wallets you recorded when the deal opened.

### Can the monitor see that funds are still held?

Yes. If the balance matches the deposit and none of the vault's successful transactions took tokens out, the status is held. That is a read of current state, so run it again as the deal ages.

### Should I poll or subscribe?

Subscribe when you watch many vaults. A notification names the transaction, and you run the same reads once for it. Poll for a handful of deals or as a safety net.

### What does one check cost on Carbium?

One balance read costs 10 cells, the signature page costs 50 and each getTransaction costs 50. Five transactions make a check of 310 cells.

## Related

- [Account notification fields](https://carbium.sh/library/howsolana/account-notification-fields) (How to use Solana, HS0037)
- [Stablecoin settlement checks](https://carbium.sh/library/usecase/stablecoin-settlement-checks) (Use cases, UC0003)
- [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#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
