---
id: I0150
title: "Home Assistant wallet sensor"
url: https://carbium.sh/library/integrate/home-assistant-wallet-sensor
collection: Integrations
category: No-code automation
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Home Assistant wallet sensor

A short Node script asks your Carbium RPC for one wallet's SOL balance and prints it as one line of JSON. Home Assistant runs it on a timer and keeps the result as a sensor, with the slot and lamports attached.

## What the sensor reports

The sensor is a single script, `main.ts`. It reads the SOL balance of one wallet and prints one line of JSON. Home Assistant's `command_line` integration runs that line on an interval you choose and takes the balance as the sensor state. The wallet address, the lamport count and the slot of the read go into the attributes. The script keeps no state and writes no file, so restarting Home Assistant changes nothing it reads.

A balance read covers one account only. A wallet that holds SOL and tokens shows just its SOL here, since each token balance lives in a separate token account. The slot names the point in the chain that the number describes, which matters when you compare two sensors read at different minutes.

## Carbium's side: one key, one read

Each request goes to the [RPC endpoint](https://carbium.sh/docs/endpoints) at `https://services.carbium.sh`, with the key placed in the [`x-api-key` header](https://carbium.sh/docs/auth). The script builds its transport once, at start, and takes the key from `CARBIUM_KEY` alone. Limits attach to the account, so all keys on it spend one budget, as laid out under [limits](https://carbium.sh/docs/limits).

The read is `getBalance` at `confirmed`, and the script passes that level explicitly. The library would pick `confirmed` by default, yet a reader should see the level in the call itself.

If a call exceeds its rate, Carbium holds it once and serves it when the cells refill within 1 s. Beyond that point the answer is 429 with a retry-after hint, covered under [limits](https://carbium.sh/docs/limits). The script makes no retry of its own. It prints the error and exits, and Home Assistant's next scheduled run acts as the retry.

## The Home Assistant side

Store the key in the environment that launches Home Assistant, whether a Docker environment block or a systemd unit, and leave it out of `configuration.yaml`. That file travels into backups and gets pasted into bug reports.

Next, add one sensor under `command_line` with these keys:

- `name: Wallet SOL`
- `command: node /config/wallet/main.ts <wallet address>`
- `unit_of_measurement: SOL`
- `value_template` set to `{{ value_json.state }}`
- `json_attributes_path: $.attributes`
- `scan_interval: 60`

Home Assistant executes the command on a host where Node 24 is installed. The official Home Assistant container ships without Node, so run the script on a host that has it, or in a container you build with Node added, and point the command at that location.

## The script

Run `npm install @solana/kit@8.6.0` in the folder and set `type` to `module` in `package.json`. Node 24 removes the type annotations on load.

`main.ts` (run: `node main.ts`)

```ts
// I0150 · Home Assistant wallet sensor
// https://carbium.sh/library/integrate/home-assistant-wallet-sensor
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium key.");
  process.exit(1);
}

const solana = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const COMMITMENT = "confirmed" as const;
const timeout = () => AbortSignal.timeout(10_000);

// A busy program's newest transactions; the first fee payer found becomes the test wallet.
const probeProgram = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");

async function pickTestWallet(): Promise<string> {
  const rows = await solana.getSignaturesForAddress(probeProgram, { limit: 5 }).send({ abortSignal: timeout() });
  for (const row of rows) {
    const tx = await solana
      .getTransaction(row.signature, { encoding: "json", commitment: COMMITMENT, maxSupportedTransactionVersion: 1 })
      .send({ abortSignal: timeout() });
    if (tx !== null) return String(tx.transaction.message.accountKeys[0]);
  }
  throw new Error("no recent transaction found to pick a test wallet");
}

// One SOL is 1e9 lamports: pad to ten digits, then split off the last nine.
function solText(lamports: bigint): string {
  const digits = lamports.toString().padStart(10, "0");
  return `${digits.slice(0, -9)}.${digits.slice(-9, -5)}`;
}

async function main(): Promise<void> {
  const wallet = process.argv.slice(2)[0] ?? (await pickTestWallet());
  const owner = address(wallet);
  const res = await solana.getBalance(owner, { commitment: COMMITMENT }).send({ abortSignal: timeout() });
  const lamports = res.value;
  const out = {
    state: solText(lamports),
    attributes: { wallet, lamports: lamports.toString(), slot: res.context.slot.toString() },
  };
  process.stdout.write(`${JSON.stringify(out)}\n`);
}

main().catch((err: unknown) => {
  console.error("wallet read failed:", err instanceof Error ? err.message : String(err));
  process.exit(1);
});
```

The first argument is the wallet. Without one, the script chooses a test wallet from the newest five signatures of the SPL Token program, taking the fee payer of the first transaction the node returns. Real use passes an address, so that lookup never runs.

Mainnet has v1 transactions, so the lookup requests [getTransaction](https://carbium.sh/docs/rpc) with `maxSupportedTransactionVersion: 1`. Leaving it out gets -32015 back for a v1 transaction. The address is validated before the balance call, so a typo fails straight away.

The state is the balance in SOL, truncated to four decimals. The exact lamport count goes into the attributes as a string, and the arithmetic runs on integers, so no digit is lost to floating point.

## Run it once, then schedule it

Export `CARBIUM_KEY` in your shell, then run `node main.ts` with a wallet address after it. The script prints one JSON line and exits with status 0. Run it with no argument once as well, to watch the test path work.

Once the line looks right, the same command goes into Home Assistant. The script writes nothing to disk, so its folder can be mounted read-only.

## What it spends

A sensor with an address set makes one `getBalance` call per run. The test path spends more: one `getSignaturesForAddress` call at 50 cells, and up to five `getTransaction` calls at 50 cells each. On Free, `getTransaction` allows 0.24 req/s and `getSignaturesForAddress` allows 0.24 req/s too, per the [rpc table](https://carbium.sh/docs/rpc).

A 60 second scan interval means one read a minute per sensor. Every sensor on the account draws on the same budget as the app, so on a busy account a sensor can get a 429 even when the sensor itself has been quiet.

## Where it ends

- The sensor reads SOL only. Token balances need reads of their own token accounts, which this script does not make.
- A read shows the account at the moment of the call. A transfer that lands between two runs appears on the next run.
- Home Assistant pulls on its scan interval. The script never pushes, so an alert on a change waits for the next scan.
- The fallback wallet comes from a busy program's recent traffic and changes from run to run. Use it to test the path only.
- Carbium's address index reaches 30 days back at most, and `getTransaction` can answer null for an older signature it still lists. The lookup skips a null answer and moves to the next signature.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The command stops with `Set CARBIUM_KEY to your Carbium key.` and Home Assistant shows no value. | Set `CARBIUM_KEY` in the environment that starts Home Assistant, and also in your shell if you test there, then restart Home Assistant. |
| The log reads `wallet read failed:` followed by an error from the address check, and the sensor keeps its last value. | Paste the wallet's public address. A valid address is base58 text that decodes to 32 bytes, so a transaction signature fails the check. A token mint passes it too, and its balance says nothing about a wallet. |
| The log reads `wallet read failed: HTTP error (429)` and mentions a retry-after hint. | Lengthen `scan_interval`, and cut traffic from other keys on the same account, since they share one budget. |
| The sensor reads 0 for a wallet you know holds SOL. | Confirm the address is the wallet itself. A token account holds only rent lamports, so its balance looks tiny. |
| The test path fails with `no recent transaction found to pick a test wallet`. | Pass a wallet address on the command line. The lookup needs a recent signature the node still returns, so treat it as a test path only. |

## Questions

### Can the sensor show a token balance too?

Not this script. A token balance comes from the token account for that mint, a separate read this script leaves out. Add a second sensor built on that read if you need one.

### Why four decimals in the state but lamports in the attributes?

The state is for display in Home Assistant, where four decimals stay readable. The lamport count is the exact figure and sits in the attributes as a string.

### How often can the sensor run on my plan?

Every sensor on the account shares that budget with the app. Check the [limits page](https://carbium.sh/docs/limits) for the rate your plan gives this class of read, and set the scan interval so the sum fits.

## Related

- [Wallet watch list at scale](https://carbium.sh/library/integrate/wallet-watch-list-at-scale) (Integrations, I0011)
- [Wallet activity tracker](https://carbium.sh/library/blockchainideas/wallet-activity-tracker) (Blockchain ideas, BI0005)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
