library / Integrations / Chat and notifications / I0120
Email renewal reminders
A small Node job reads subscription rows from SQLite, checks each customer's token balance through Carbium a few days before the renewal date, and posts one email per renewal to your mail API saying whether the balance covers the price.
What the job does
Solana has no pull payment. Nothing on chain charges a wallet on a schedule unless the wallet has approved a delegate for the token. In most recurring setups a renewal is therefore a date in your database and a customer who has to have the money ready when it arrives. This job covers the polite part of that arrangement.
It keeps one row per subscription in a local SQLite file: the customer's email, the paying wallet, the billing token's mint, the price in base units and the renewal time. Each run selects the rows whose renewal falls within the next 3 days, reads the wallet's balance of that token, and sends one email per row. The email says either that a top-up is needed, with the missing amount, or that the balance already covers the price.
| Case | Subject line | Body |
|---|---|---|
| Balance below the price | Renewal on 2026-12-01: top up needed | Names the wallet, the balance, the price and the amount to add. |
| Balance at or above the price | Renewal on 2026-12-01: balance covers it | Names the wallet, the balance and the price, and says nothing is needed. |
Each renewal date gets at most one email. The row stores the date it last reminded for, and that mark moves only after the mail API has answered with a success status. A failed send leaves the row unmarked, so the next run tries it again. When your app takes the payment, it moves the renewal time to the next period. The new date has no reminder yet, so the cycle starts over.
The Solana side: one balance over every token account
A wallet can own more than one token account for the same mint, so the balance is a sum. The job calls getTokenAccountsByOwner with the mint as the filter and jsonParsed encoding. Each returned account carries its raw amount as a string, and the job adds them as BigInt in base units. A mint filter matches accounts of that mint under either token program, so Token-2022 mints work without a branch.
Prices are stored in base units as well. USDC has 6 decimals, so a price of 5 USDC is 5000000. Comparing and subtracting in base units keeps the missing amount exact, and you format it for people only when you template the email.
The call reads at confirmed commitment. A reminder reports a balance that can still change before the renewal, so the level matters little here. What matters is that the number arrives a few days early and the customer still has time to act on it.
Native SOL has no token account. If you bill in SOL, swap the call for getBalance on the wallet and keep the rest of the job as it is.
The Carbium side: one read per due subscription
The client points at the RPC endpoint https://services.carbium.sh and sends the key in the `x-api-key` header. A run makes one getTokenAccountsByOwner call for each subscription that is due and none when nothing is due, so a daily run over a few thousand customers stays small whatever the size of the table.
Limits are per account, so the job shares its budget with every other key on the account. If the account is over its rate, a call can come back as a 429 with a retry-after hint. The job treats that like any failed read: it logs the failure, leaves the row unmarked and picks it up on the next run. The reads run together in Promise.allSettled, so one failing wallet does not hide the others, and each failure prints beside the email address it belongs to.
The email side: one JSON POST
Node has no built-in SMTP client, so the job posts JSON to a URL you choose. The body is {"to", "subject", "text"}, with an optional bearer token from MAIL_API_KEY. Mail providers name their fields differently, so point MAIL_API_URL at a relay you run, or at a small adapter in front of your provider's send endpoint, and map those three fields there.
With MAIL_API_URL unset the job runs dry. It prints the email it would send and marks nothing, so you can check the wording and the amounts against real wallets before any customer sees a message.
The script
Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load, and node:sqlite ships with it. CARBIUM_KEY is required and the script exits with a message when it is missing. CARBIUM_RPC_URL, MAIL_API_URL, MAIL_API_KEY and LEAD_DAYS are optional, and LEAD_DAYS defaults to 3.
// I0120 · Email renewal reminders// https://carbium.sh/library/integrate/email-renewal-reminders// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const mailUrl = process.env.MAIL_API_URL; // unset: dry run, prints the mail and marks nothingconst leadDays = Number(process.env.LEAD_DAYS ?? 3);const DAY = 86_400_000;const db = new DatabaseSync("renewals.db");db.exec( "create table if not exists subs (email text, wallet text, mint text, price text, renews_at integer, reminded_for integer default 0, primary key (email, wallet, mint))",);// Optional arguments add or update one row: email wallet mint price-in-base-units days-until-renewalconst [email, wallet, mint, price, days] = process.argv.slice(2);if (email && wallet && mint && price && days) { db.prepare( "insert into subs (email, wallet, mint, price, renews_at) values (?, ?, ?, ?, ?) on conflict (email, wallet, mint) do update set price = excluded.price, renews_at = excluded.renews_at", ).run(email, address(wallet), address(mint), BigInt(price).toString(), Date.now() + Number(days) * DAY);}type Sub = { email: string; wallet: string; mint: string; price: string; renews_at: number };type Parsed = { parsed: { info: { tokenAmount: { amount: string } } } };async function remind(s: Sub): Promise<string> { const res = await rpc .getTokenAccountsByOwner(address(s.wallet), { mint: address(s.mint) }, { encoding: "jsonParsed", commitment: "confirmed" }) .send({ abortSignal: AbortSignal.timeout(10_000) }); // A wallet can own several token accounts for one mint: sum them in base units. const balance = res.value.reduce((sum, a) => sum + BigInt((a.account.data as unknown as Parsed).parsed.info.tokenAmount.amount), 0n); const need = BigInt(s.price); const short = balance < need; const mail = { to: s.email, subject: `Renewal on ${new Date(s.renews_at).toISOString().slice(0, 10)}: ${short ? "top up needed" : "balance covers it"}`, text: `Wallet ${s.wallet} holds ${balance} base units of ${s.mint}; the renewal costs ${need}. ` + (short ? `Add at least ${need - balance} before the renewal date.` : "Nothing to do."), }; if (!mailUrl) return `dry run, would send ${JSON.stringify(mail)}`; const headers: Record<string, string> = { "content-type": "application/json" }; if (process.env.MAIL_API_KEY) headers.authorization = `Bearer ${process.env.MAIL_API_KEY}`; const sent = await fetch(mailUrl, { method: "POST", headers, body: JSON.stringify(mail), signal: AbortSignal.timeout(10_000) }); if (!sent.ok) throw new Error(`mail API answered ${sent.status}`); db.prepare("update subs set reminded_for = ? where email = ? and wallet = ? and mint = ?").run(s.renews_at, s.email, s.wallet, s.mint); return "sent";}const due = db .prepare("select email, wallet, mint, price, renews_at from subs where renews_at - ? <= ? and reminded_for <> renews_at") .all(Date.now(), leadDays * DAY) as unknown as Sub[];const results = await Promise.allSettled(due.map((s) => remind(s)));results.forEach((r, i) => console.log(due[i]?.email, r.status === "fulfilled" ? r.value : `failed: ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`),);console.log(`${due.length} renewals due within ${leadDays} days`);
run: node main.ts
Add a subscription and schedule the run
Five arguments add or update a row: email, wallet, mint, price in base units and the number of days until renewal. For example, node main.ts [email protected] <wallet> <mint> 5000000 2 stores a 5 USDC renewal two days out and, because that is inside the lead time, checks it in the same run. Your app normally writes the rows itself with the same columns, and the arguments are a quick way to test one.
Run the job once a day from cron or a systemd timer. The date mark stops a second run on the same day from mailing anyone twice.
Where it ends
- It charges nothing and signs nothing. It reads a balance and sends an email; the payment itself is a transfer your customer makes or a delegate pull your own code builds.
- It does not check whether the wallet has approved a delegate. The subscription allowance monitor covers that side of a recurring setup.
- The balance is a reading from the moment of the run. A customer can spend it a minute later, and one who tops up after the email gets no second message.
- One email per renewal date. A 7-day and a 1-day reminder need the row to remember which lead was sent, which is a small change to the mark.
- A success status from your mail API means it accepted the message, and the job cannot see whether it reached an inbox.
- It has no templates, unsubscribe handling or localisation. Those belong in the mail relay or in your app.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every wallet fails with HTTP error (401) in the log. | The key is wrong or cut short. An unknown key gets a 401 at the door, so check that CARBIUM_KEY holds the whole key and that nothing else overrides CARBIUM_RPC_URL. |
| The log shows mail API answered 400 or 401 and the same customer is retried every run. | The relay rejected the body or the token. Check MAIL_API_URL and MAIL_API_KEY, and that the relay accepts the to, subject and text fields. The row stays unmarked until a send succeeds, so the next run delivers it. |
| An email says top up needed, yet the customer holds the funds. | The funds sit in another wallet, or the stored mint is not the token the customer holds. Compare the row's wallet and mint with the transfer the customer made, and remember that a wrapped or bridged copy of a token has its own mint. |
| The same customer gets a reminder on every run, or never gets one, and the row's renewal date keeps sliding forward. | The test form with arguments was left in a daily job. It rewrites the renewal time on every run: a date inside the lead time is a new date each run and mails again, and a date outside it never comes due. Remove the arguments and let your app write the dates. |
| The insert stops with an invalid address error. | A wallet or mint string is mistyped or cut short. The script checks both before it writes the row, so nothing half-written stays in the table. |
Questions
Can Solana charge a customer automatically every month?
Only when the customer's token account has approved a delegate, and then your own code builds the transfer each period. Without an approval the customer has to send each payment, which is the case this reminder is for.
Why a local SQLite file for the subscriptions?
node:sqlite comes with Node 24, so the job needs no database server. The due list is one select, and you can point the same query at your own table.
How many RPC calls does a run make?
One getTokenAccountsByOwner per due subscription, and no call when nothing is due. All of them count against the account's shared limits.
Does the balance include the token accounts a wallet owns for other mints?
No. The mint filter returns only accounts of the billing token, and the job sums those. Accounts for other mints do not enter the number.