services
Get a key

library / AI and blockchain / SI0007

Agent wallet watcher

A read-only Node watcher for an agent's wallet. It reports the balance and recent signatures, and flags any transaction the agent's own signer never recorded.

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

01

Can an agent own a wallet?

Yes, in the only sense the chain knows. A Solana wallet belongs to whoever holds its keypair, and nothing on chain asks whether the holder is a person, a service or a language model's tool loop. An agent that can sign owns the wallet the way anyone does.

What matters is which process holds the key and what limits sit on it. A model that can see the key can leak it through a prompt injection, a log line or a tool result. So the key belongs in a separate signer process, and the agent asks that process for a transaction with an amount and a destination the signer checks against its own limits. Those limits live in your signer code, and the watcher sits beside it.

The watcher is worth building first because it holds no key and cannot lose funds. It reports the wallet's balance and flags any transaction the signer did not record sending. If the key leaks or the signer misbehaves, the watcher is where you see it.

02

Signer, agent and watcher

Three pieces, each with only the access it needs. The signer holds the keypair, builds and sends transactions, and writes each signature into a SQLite table named sent before it sends. The agent holds no key and asks the signer for transactions. The watcher holds the public address and the Carbium key, and reads the sent table.

The signer sends through the same RPC endpoint. sendTransaction is served, at 20 cells without preflight and 70 with it. Its code is yours to write; this file holds no key and never calls it.

The watcher's check is one lookup. A signature in sent is own. A signature the signer never recorded is UNEXPECTED. That covers an incoming deposit and a stolen key used from elsewhere, and this file cannot tell them apart. A deposit is not signed by the wallet and a misused key is, so a `getTransaction` read plus a check for the wallet among the signers splits the two.

03

The watcher file

One file. Node 24 runs the TypeScript directly, @solana/kit 8.6.0 makes the RPC calls, and node:sqlite and the global WebSocket come with Node. Set CARBIUM_KEY and pass the wallet address as the first argument; the file exits with a message when either is missing. CARBIUM_RPC_URL and CARBIUM_WS_URL override the two endpoints, which default to https://services.carbium.sh and wss://services.carbium.sh. SENT_DB is the path to the signer's database file. The watcher opens it read-only, so a mistyped path stops the run with an error. Left out, it uses an empty in-memory table.

main.ts
// SI0007 · Agent wallet watcher// https://carbium.sh/library/si/agent-wallet-watcher// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Agent wallet watcher, read only. Run: CARBIUM_KEY=... node main.ts <wallet address>import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;const target = process.argv[2];if (!key || !target) {  console.error("Set CARBIUM_KEY to your Carbium API key and pass a wallet address.");  process.exit(1);}const apiKey: string = key;const wallet = address(target);const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": apiKey },  }),);const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");wsUrl.searchParams.set("api-key", apiKey);// The signer writes each signature here before it sends. The watcher opens the file read-only,// so a mistyped path fails loudly. Only the in-memory default creates its own table.const path = process.env.SENT_DB;const db = path ? new DatabaseSync(path, { readOnly: true }) : new DatabaseSync(":memory:");if (!path) db.exec("create table if not exists sent (signature text primary key)");const recorded = db.prepare("select 1 from sent where signature = ?");const seen = new Set<string>();const readBalance = async () => (await rpc.getBalance(wallet, { commitment: "confirmed" }).send()).value;let balance = await readBalance();console.log(`balance ${balance} lamports`);function report(signature: string, failed: boolean): void {  if (seen.has(signature)) return;  seen.add(signature);  const label = recorded.get(signature) ? "own       " : "UNEXPECTED";  console.log(`${label} ${signature}${failed ? " (failed)" : ""}`);}async function backfill(): Promise<void> {  const recent = await rpc.getSignaturesForAddress(wallet, { limit: 5, commitment: "confirmed" }).send();  for (const entry of [...recent].reverse()) report(entry.signature, entry.err !== null);}let queue: Promise<void> = Promise.resolve();const ws = new WebSocket(wsUrl);ws.addEventListener("open", () => {  const params = [{ mentions: [wallet] }, { commitment: "confirmed" }];  ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params }));  queue = queue.then(backfill).catch((e) => console.error("backfill failed:", (e as Error).message));});ws.addEventListener("message", (event) => {  const msg = JSON.parse(String(event.data));  if (msg.error) {    console.error("subscription refused:", msg.error.message);    process.exit(1);  }  const value = msg.params?.result?.value;  if (!value) return;  queue = queue    .then(async () => {      report(value.signature, value.err !== null);      const next = await readBalance();      if (next !== balance) console.log(`balance ${next} lamports, change ${next - balance}`);      balance = next;    })    .catch((e) => console.error("read failed:", (e as Error).message));});ws.addEventListener("close", () => {  console.error("socket closed, exiting so a supervisor restarts the watcher");  process.exit(1);});

run: node main.ts <wallet address>

On start it reads the balance, opens the socket and subscribes with logsSubscribe and a mentions filter for the wallet, then reads the five latest signatures and reports them oldest first. The subscription and that read overlap on purpose, and seen drops any signature reported twice. Every event goes through one promise queue, so reports and balance reads stay in order.

logsSubscribe is the trigger because accountSubscribe stays silent for a plain SOL wallet. The log event says a transaction touched the wallet, and getBalance says what it did to the balance. Failed transactions arrive too, with err set. With no SENT_DB every signature prints UNEXPECTED, which is the right answer when no signer has recorded anything.

04

What the watcher prints

LineMeaningWhat to do
balance 1234 lamportsThe start-up read at confirmed. 1 SOL is 1,000,000,000 lamports.Keep it as the baseline.
own <signature>The signature is in sent.Nothing.
UNEXPECTED <signature>A transaction mentions the wallet and the signer never recorded it.Open it and decide: a deposit or misuse.
(failed) after a signatureThe transaction landed with an error. A failed transaction can still pay its fee.Find out why it was sent.
balance 1250 lamports, change 16A balance read after an event differs from the last one.Match it to the signature above it.

Every call asks for confirmed, so a line can in rare cases describe a transaction on a fork that is later dropped. A watcher that must never print something that can still change can ask for finalized at little extra delay.

05

Cost, keys and one client

The start-up signature read costs 50 cells and runs once per start. The rates for it are 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro. A supervisor that restarts the watcher in a tight loop will soon hit that ceiling on Free, so put a pause between restarts.

The subscription opens at the middle weight, 25 credits, then costs 20 credits per MiB sent. A refused subscription is free. Connection and subscription counts are capped per account by tier, and Free carries 5 sockets, so one socket with one subscription per wallet is the shape to scale from. Size the per-event `getBalance` read against your tier's rate before you add wallets.

Limits are per account, and an account's keys share one budget, so another service on the same account can spend what the watcher needs. The file builds one RPC client and one socket and keeps them. It prints neither the URL nor the socket's error object, so the key stays out of the output.

06

Where it ends

  • The watcher reports after the fact. A transaction is printed once it lands at confirmed. Stopping a bad transfer needs limits in the signer, before it signs.
  • A recorded signature is not a safe one. A signer that was talked into paying the wrong address records the signature, and the watcher prints own. Judging destination and amount is policy in the signer.
  • mentions matches transactions that list the wallet's address. A token transfer into the wallet's token account lists the token account and may never list the wallet, so watch each token account you care about with its own subscription.
  • The sent table is only as honest as whoever can write it. Keep the signer on a host the agent cannot reach, and give the agent no write access to the database file.
  • The start-up read takes five signatures. An outage that spans more than five transactions leaves a gap; raise limit to cover it. getSignaturesForAddress pages come from Carbium's own address index, which keeps up to 30 days, so older history is not served and an empty page past that is the index's age limit.
  • There is no reconnect inside the file. It exits with status 1 when the socket closes, and a supervisor restarts it.
  • The printed balance change can lag by one event, because the read may run before the node's view includes the transaction.
07

When it goes wrong

what goes wrongwhat to do
The watcher stays silent while the balance changes.The subscription is accountSubscribe, which stays silent for a plain SOL wallet. Use logsSubscribe with mentions and read getBalance on each event, as the file does.
Every transaction the agent sends shows as UNEXPECTED.SENT_DB is unset or points at a file other than the signer's, or the signer recorded the signature after the notification arrived. A signed transaction carries its signature before it is sent, so insert the row first and send second.
The socket closes and nothing reports for hours.The file exits with status 1 on close. Run it under a supervisor that restarts it after a pause. The start-up read then reports what landed in the gap, up to five signatures.
The start-up read answers 429.The account is over its rate for this read, so wait the retry-after time the 429 carries before the next restart. Limits are per account, so other keys on the account may be spending the budget.
The subscription is refused and the watcher exits.Connection and subscription counts are capped per account by tier, and Free carries 5 sockets. A refused subscription is free. Close sockets you do not use, or put several wallets on one socket.
The printed balance change is one event behind.The balance read ran before the node's view included the transaction. The next event prints the full change.
08

Questions

Can an AI agent hold its own private key?

Nothing on chain stops it, because a wallet belongs to whoever signs for it. Keep the key in a signer process the agent cannot read, and let the agent ask that process for a transaction within limits you set.

Does the watcher sign or send anything?

No. It holds a public address and the Carbium key, makes read calls and one subscription, and never touches a keypair. Sending is the signer's job.

Why does it read the balance after every event?

accountSubscribe stays silent for a plain SOL wallet, so the log event is the trigger and getBalance is the read.

How far back can it look?

The start-up read takes five signatures, and limit raises that. The address index keeps up to 30 days, and an empty page past that is the index's age limit.

Can the agent read this output?

Yes, and that is a sensible use: pass the lines to the agent as its view of its own wallet. Read-only model tools shows a method allowlist that keeps a model's own calls read-only.