services
Get a key

library / Integrations / I0033

Vercel OG wallet image

A card builder that reads a wallet's SOL balance, token account count and latest activity through Carbium and returns an element tree for next/og, with a Node check, the Vercel route that wraps it, caching and failure handling.

By Carbium · Serverless and edge · I0033 · updated 2026-11-22

01

How the pieces fit

A link to a wallet page unfurls in a chat or a feed as a preview image. That image comes from an og:image URL on your site, and a Vercel route can answer that URL with a PNG drawn on the fly. ImageResponse from next/og does the drawing: it takes an element tree, lays it out with Satori and returns a PNG.

The file below is the data half. card(rpc, owner) makes three reads for one wallet, turns them into an element tree and returns it. The route file wraps it: parse the address, call card, hand the tree to ImageResponse at 1200 by 630. The file also runs under Node 24 as a check, so you see the tree and the numbers before anything is deployed.

Satori is not a browser. It lays out with flexbox, so every div that holds more than one child needs display: flex, and it has no CSS grid. The helper h in the file sets display: flex on every box so a forgotten style never breaks the layout. It also sets key: null, which the ReactElement type that ImageResponse expects requires.

02

What the card reads

Three calls, all read-only, all started together, so the card waits for one round trip:

  • getBalance for the wallet gives lamports. The file prints them as SOL with two decimals using integer division on a bigint, so no float ever touches an amount.
  • getTokenAccountsByOwner with the classic token program id counts the wallet's token accounts. The call asks for base64 with a dataSlice of length 0, so the response carries addresses and no account data.
  • getSignaturesForAddress with limit: 1 gives the newest signature and its blockTime, which becomes the line 12 min ago.

The label says token accounts because a wallet can own more than one token account for one mint. The count also leaves out Token-2022 accounts, which live under a different program id.

Each of the three reads settles on its own under Promise.allSettled. A read that fails shows unavailable on the card, and its name goes into a failed list in the result.

03

The Carbium side: key and client

Calls go to the RPC endpoint at https://services.carbium.sh, with the key in the x-api-key header. In a Vercel project the key lives in an environment variable named CARBIUM_KEY, added under Settings, Environment Variables, and never in a variable whose name starts with NEXT_PUBLIC_, since that prefix ships the value to the browser. The image route runs on the server, so the key stays there.

connect builds the client from createDefaultRpcTransport and createSolanaRpcFromTransport. The Edge runtime exposes process.env for deployed variables, so the same function serves the route and the Node check. The route keeps the client in a module variable so a warm instance reuses it.

The check run takes an address on the command line. With none, busyWallet reads the newest signatures of a busy program, fetches the first transaction it can read with maxSupportedTransactionVersion: 1, and uses the fee payer. Mainnet carries v1 transactions, and a getTransaction call with the version absent or 0 answers -32015 for one. getTransaction can also answer null for a signature the index lists below the validator's ledger floor, which is why the loop moves on to the next signature.

04

The file

Install with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. Export CARBIUM_KEY, then run node main.ts <wallet address> to print the element tree and the failed list. With no address it finds an active wallet itself.

main.ts
// I0033 · Vercel OG wallet image// https://carbium.sh/library/integrate/vercel-og-wallet-image// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress } from "@solana/kit";const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const JUPITER = address("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");export function connect(env: { CARBIUM_KEY?: string; CARBIUM_RPC_URL?: string }) {  if (!env.CARBIUM_KEY) throw new Error("Set CARBIUM_KEY.");  const url = env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";  return createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": env.CARBIUM_KEY } }));}type Rpc = ReturnType<typeof connect>;// Integer math on bigint: lamports to SOL with two decimals, no float.const sol = (l: bigint) => `${l / 1_000_000_000n}.${String((l % 1_000_000_000n) / 10_000_000n).padStart(2, "0")}`;function ago(t: bigint | null | undefined) {  if (t === undefined) return "none in 30 days";  if (t === null) return "unknown";  const min = Math.max(0, Math.floor((Date.now() / 1000 - Number(t)) / 60));  return min < 120 ? `${min} min ago` : min < 2880 ? `${Math.floor(min / 60)} h ago` : `${Math.floor(min / 1440)} d ago`;}// Satori needs display:flex on any box with several children; h always sets it.// key: null makes the tree a valid ReactElement for next/og.const h = (style: Record<string, string | number>, ...children: unknown[]) => ({  type: "div",  key: null,  props: { style: { display: "flex", ...style }, children },});const row = (label: string, value: string) =>  h({ flexDirection: "column", marginRight: 60 }, h({ fontSize: 28, color: "#9ca3af" }, label), h({ fontSize: 56, color: "#ffffff" }, value));// The element tree for ImageResponse from next/og. Commitment left out: kit 8.6.0 sends confirmed.export async function card(rpc: Rpc, owner: string) {  const who = address(owner);  const abortSignal = AbortSignal.timeout(5_000);  const [bal, tok, sigs] = await Promise.allSettled([    rpc.getBalance(who).send({ abortSignal }),    rpc.getTokenAccountsByOwner(who, { programId: TOKEN_PROGRAM }, { encoding: "base64", dataSlice: { offset: 0, length: 0 } }).send({ abortSignal }),    rpc.getSignaturesForAddress(who, { limit: 1 }).send({ abortSignal }),  ]);  const failed = ([["balance", bal], ["token accounts", tok], ["activity", sigs]] as const)    .filter(([, r]) => r.status === "rejected")    .map(([name]) => name);  const tree = h(    { width: "100%", height: "100%", flexDirection: "column", justifyContent: "center", padding: 80, background: "#0b1020" },    h({ fontSize: 40, color: "#facc15" }, `${owner.slice(0, 4)}...${owner.slice(-4)}`),    h(      { marginTop: 48 },      row("SOL balance", bal.status === "fulfilled" ? sol(bal.value.value) : "unavailable"),      row("Token accounts", tok.status === "fulfilled" ? String(tok.value.value.length) : "unavailable"),      row("Last activity", sigs.status === "fulfilled" ? ago(sigs.value[0]?.blockTime) : "unavailable"),    ),  );  return { owner, failed, tree };}// Check run with no address: the fee payer of a recent transaction on a busy program.async function busyWallet(rpc: Rpc) {  const sigs = await rpc.getSignaturesForAddress(JUPITER, { limit: 5 }).send();  for (const s of sigs) {    const tx = await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send();    if (tx) return tx.transaction.message.accountKeys[0].pubkey;  }  throw new Error("no readable transaction on the newest signatures");}// Node check only: node main.ts [address]. The Vercel route imports card and connect instead.if (globalThis.process?.argv?.[1]?.endsWith("main.ts")) {  try {    const rpc = connect(process.env);    const owner = process.argv[2] ?? (await busyWallet(rpc));    if (!isAddress(owner)) throw new Error(`not a Solana address: ${owner}`);    console.log(JSON.stringify(await card(rpc, owner), null, 1));  } catch (e) {    console.error(e instanceof Error ? e.message : e);    process.exit(1);  }}

run: node main.ts

05

The Vercel route

In a Next.js app put the route at app/api/og/route.tsx with export const runtime = "edge". At module scope it holds const rpc = connect(process.env). The handler reads address from the query string, checks it with isAddress and answers 400 for anything else. For a valid address it returns new ImageResponse(tree, { width: 1200, height: 630, headers }), where tree is (await card(rpc, address)).tree.

Set the cache on that response through headers in the options. A header such as public, s-maxage=300, stale-while-revalidate=3600 lets Vercel's CDN answer repeat requests for the same URL without running the route, so the Carbium calls happen about once per wallet per region in that window. Point the page's og:image meta tag at /api/og?address=<wallet>.

A shared link is fetched by several crawlers within a few seconds. Each crawler fetch of an uncached URL costs three reads, so the CDN header keeps a shared link to one set of reads per window.

06

What it costs against your limits

getSignaturesForAddress costs 50 cells a call, and its rate is 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro. On Free its 0.24 req/s alone allows about one uncached card every four seconds, which is why the cache header matters on a small plan.

Limits are per account, so every key on the account, the Vercel project's included, shares one budget. A call over its rate gets a 429, and the card then shows unavailable for that field. For alerts on that rate, see RPC rate-limit alerts. For reading one token balance of a wallet, see SPL token balance.

07

Where it ends

  • The Node check covers the three reads and the element tree. Render the PNG under vercel dev or a preview deployment before you rely on the route.
  • Last activity comes from an address index that keeps up to 30 days. A wallet idle for longer shows none in 30 days, and it may have older transactions.
  • The balance is the SOL balance only. Token amounts, prices and names of tokens are not on the card.
  • Token accounts under Token-2022 are not counted, and a wallet with several accounts for one mint counts each.
  • The card carries no wallet name or avatar. Add those from your own database.
  • One route makes three Carbium calls per uncached image. Without a CDN cache or your own store in front, traffic to the route maps straight to Carbium traffic.
08

When it goes wrong

what goes wrongwhat to do
The card shows unavailable on every field.All three reads answered 401, so the key that reaches Carbium is wrong or partial. Check that the stored CARBIUM_KEY holds the whole key with nothing cut off, then redeploy. An unknown key gets 401.
The route answers 500 with the error Set CARBIUM_KEY.The variable is missing for the deployment target you are running (Production, Preview or Development), or the project was not redeployed after it was added. Add it for that target and redeploy.
Some cards show unavailable on activity under load.The getSignaturesForAddress rate is spent, often by other keys on the same account. Add the CDN cache header, raise s-maxage, or move to a plan with a higher rate.
ImageResponse fails with an error about display: flex.A box with several children lacks display: flex. Build every box with the h helper, which sets it, and keep to flexbox styles, since Satori has no grid.
The check run exits with a -32015 message from busyWallet.A getTransaction call went out without maxSupportedTransactionVersion: 1, and mainnet's v1 transactions answer -32015 without it. Keep the value in the options object as written in the file.
Last activity shows none in 30 days for a wallet you know is old and active.Check the address for a typo first. An empty page means nothing signed in the index's 30 days; the wallet may have older transactions.
09

Questions

Can I run this on the Node runtime instead of Edge?

Yes. The file uses only fetch and standard types, so it runs on either runtime. Edge starts faster for an image route, and Node gives you more room if you add a custom font.

Why not read the wallet in the browser and draw the image there?

A crawler fetches an image URL and runs no page script, so the image has to exist on the server. Reading server-side also keeps the Carbium key out of the browser.

How fresh is the balance on the card?

As fresh as the cache header allows. With s-maxage=300 a card can be up to five minutes old, and the read itself is at confirmed commitment because the file leaves commitment out.

How do I get more fields onto the card?

Add a read to the Promise.allSettled list and a row to the tree. Each extra read adds Carbium calls per uncached card, so check what the method costs in cells first.