---
id: I0112
title: "Telegram invoice payment check"
url: https://carbium.sh/library/integrate/telegram-invoice-payment-check
collection: Integrations
category: Chat and notifications
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Telegram invoice payment check

A short Node script takes a wallet, an amount and an invoice reference, reads the wallet's newest transactions from Carbium, decides whether the invoice is paid, and posts a paid invoice to a Telegram chat through the sendMessage URL you hold.

## What the check does

Your Telegram integration sells something and needs to know whether the buyer paid. When a buyer asks to pay, you create an invoice record with a random reference string and show the buyer three things: your wallet address, the amount in lamports and the reference to put in the transaction's memo. This script is the check that runs afterwards. It reads the wallet's newest transactions from Carbium and answers paid or not paid.

A transaction counts as the payment when it succeeded, raised the wallet's balance by at least the amount, and carried a Memo program instruction whose text contains the reference. With no reference given, any transaction that raised the balance by the amount counts, which is how you can try the script on a busy address before you have an invoice. On a match it prints one line with the signature and slot, and when two variables are set it sends the same line to the chat.

| Input | Meaning |
|---|---|
| First argument | The wallet that receives payments. |
| Second argument | Minimum amount in lamports, default 1000. |
| Third argument | The invoice reference. Left out, the memo is not checked. |
| `TELEGRAM_SEND_URL` | Optional. The full sendMessage URL for your Telegram token. |
| `TELEGRAM_CHAT_ID` | Optional. The chat that receives the answer. |

## The Solana side: signatures, then parsed transactions

The script asks `getSignaturesForAddress` for the wallet's 10 newest signatures and drops any whose `err` is set, since a failed transaction moved no money. It then fetches each remaining signature with `getTransaction` in `jsonParsed` encoding. The fetches run together in `Promise.allSettled`, so one failed fetch is printed and the rest still count.

Both calls read at confirmed commitment, written out in each config so the level is visible in the code.

`getTransaction` carries `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and a call with the field absent or set to 0 answers -32015 for one of them. Without it, a buyer who paid from a v1 transaction would show up only as a failed fetch, and that invoice would never match.

The amount is read from the transaction's balance arrays. The script finds the wallet's index among the account keys and subtracts its pre balance from its post balance. That is the wallet's net change, so a fee the wallet paid as fee payer is already inside it, and a transaction the wallet sent itself shows a negative delta that never matches. The memo comes from instructions whose program is `spl-memo`, which `jsonParsed` returns as a plain string.

A signature that `getSignaturesForAddress` lists can still make `getTransaction` answer null, because the address index reaches below the validator's ledger floor. The script reports a null as unreadable and moves on. A payment made minutes ago is not affected.

## The Telegram side: one message per paid invoice

Telegram's sendMessage method takes a chat id and a text. The script reads the whole sendMessage URL from `TELEGRAM_SEND_URL`, token included, and the chat id from `TELEGRAM_CHAT_ID`. Treat that URL as a secret, since anyone holding it can post as your integration. With either variable unset, the script only prints.

Telegram's built-in invoice message settles through its payment providers, so the Solana invoice here is ordinary message text plus a record you keep: reference, amount, wallet and state. Run the check when the buyer taps a Paid button, and again on a timer for every open invoice. Mark the record paid on the first match and store the signature with it, so one transaction can never settle two invoices.

Make the reference random, one per invoice, and long enough that nobody guesses it. A reference like `inv-8F3K2Q9M` is short enough to paste into a wallet's memo field and long enough to stay unique across thousands of invoices.

## The script

Install the one dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. The script exits with a message when `CARBIUM_KEY` is missing, and `CARBIUM_RPC_URL` is optional.

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

```ts
// I0112 · Telegram invoice payment check
// https://carbium.sh/library/integrate/telegram-invoice-payment-check
// 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.");
  process.exit(1);
}
const [wallet, minArg = "1000", reference = ""] = process.argv.slice(2);
if (!wallet) {
  console.error("Usage: node main.ts <wallet> [minLamports] [reference]");
  process.exit(1);
}
const minimum = BigInt(minArg);

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

// The parts of a jsonParsed transaction this check reads.
type Parsed = {
  slot: bigint;
  transaction: { message: { accountKeys: { pubkey: string }[]; instructions: { program?: string; parsed?: unknown }[] } };
  meta: { preBalances: (bigint | number)[]; postBalances: (bigint | number)[] } | null;
};

const listed = await rpc.getSignaturesForAddress(address(wallet), { limit: 10, commitment: "confirmed" }).send();
const sigs = listed.filter((s) => s.err === null).map((s) => s.signature);
const fetched = await Promise.allSettled(
  sigs.map((s) =>
    rpc.getTransaction(s, { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send(),
  ),
);

let paid = "";
fetched.forEach((r, i) => {
  if (paid) return; // newest first: the first match wins
  if (r.status === "rejected") {
    console.error(`${sigs[i]}: ${String(r.reason)}`);
    return;
  }
  if (r.value === null) {
    console.error(`${sigs[i]}: not readable (null)`);
    return;
  }
  const tx = r.value as unknown as Parsed;
  const at = tx.transaction.message.accountKeys.findIndex((k) => k.pubkey === wallet);
  if (at < 0 || !tx.meta) return;
  const delta = BigInt(tx.meta.postBalances[at]) - BigInt(tx.meta.preBalances[at]);
  const memos = tx.transaction.message.instructions.filter((x) => x.program === "spl-memo").map((x) => String(x.parsed));
  if (delta >= minimum && (!reference || memos.some((m) => m.includes(reference)))) {
    paid = `Invoice ${reference || "(no reference)"} paid: +${delta} lamports in ${sigs[i]} at slot ${tx.slot}`;
  }
});

console.log(
  paid || `No payment of ${minimum} lamports${reference ? ` with reference ${reference}` : ""} in the newest ${sigs.length} transactions.`,
);

const hook = process.env.TELEGRAM_SEND_URL;
const chat = process.env.TELEGRAM_CHAT_ID;
if (paid && hook && chat) {
  const res = await fetch(hook, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ chat_id: chat, text: paid }),
    signal: AbortSignal.timeout(5_000),
  });
  console.log(res.ok ? "Telegram message sent." : `Telegram answered ${res.status}.`);
}
```

## Run it

Pass the wallet, the amount and the reference: `node main.ts <wallet> 50000000 inv-8F3K2Q9M`. A paid invoice prints `Invoice inv-8F3K2Q9M paid: +50000000 lamports in <signature> at slot <slot>`. An unpaid one prints how many transactions it looked at, which tells you the check ran and found nothing.

To try it before you have an invoice, run it on a wallet that receives transfers all day and leave the reference out. The newest incoming transfer over the amount is reported.

## What a check costs against your limits

One check is one `getSignaturesForAddress` call at 50 cells and up to 10 `getTransaction` calls at [50 cells each](https://carbium.sh/docs/rpc). The two methods sit in different rate classes, and each class [absorbs bursts](https://carbium.sh/docs/limits) up to 1,024 cells, so the 500 cells of transaction reads fit in one burst on any plan.

The refill rate for `getTransaction` is 0.24 req/s on Free, 1.2 on Dev, 5 on Business and 25 on Pro. On Free, two checks back to back still fit in that burst, and a third right after them gets a 429 with a `retry-after` hint, so spread open invoices out instead of checking them all together. Limits are per account, so your other keys draw on the same budget.

## Where it ends

- It reads native SOL transfers only. A payment in a token needs the token balance arrays of the transaction instead.
- It looks at the newest 10 signatures of the wallet. A wallet that receives more than that between two checks pushes an older payment out of view; raise the limit or page back with `before`.
- It reads memos on top-level instructions. A memo written by another program through an inner instruction goes unseen.
- It does not know who paid. Anyone who sees the reference can pay it, so the reference identifies an invoice and says nothing about the sender.
- History reaches back 30 days at most, so an invoice older than that cannot be confirmed.
- It never signs or sends. A refund is a separate transaction that your own code builds.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The check prints -32015 for some signatures. | The call was made without `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions and an older value answers -32015 for them. Keep the field in the `getTransaction` config. |
| The buyer paid, and the check says there is no payment. | Open the transaction in an explorer. Common causes: the wallet put the reference in a different field, the amount is under the minimum, or the transfer went to another address. If the wallet is busy, more than 10 transactions arrived since, so raise the limit. |
| Several `getTransaction` calls fail with HTTP 429. | The account's budget for that class is spent, and `getTransaction` refills slowly on Free. Check fewer invoices at once, wait the `retry-after` seconds, or move to a plan with a higher rate. The failed signatures are printed, so the next check can start from them. |
| Telegram answers 400 or 403 and the chat gets no message. | The chat id is wrong, or the person has not started a conversation with your integration. Send it any message from that chat first, then read the chat id from Telegram's getUpdates answer. |
| A signature is listed and `getTransaction` returns null. | The address index reaches below the validator's ledger floor, so an older signature can be listed and unreadable. Check recent payments only, and treat null as not readable. |
| An old invoice never matches and the log shows nothing wrong. | The wallet's address history stops at 30 days. Confirm older invoices by hand from the signature the buyer sends you. |

## Questions

### Can Telegram's own invoice button take a Solana payment?

Telegram's built-in invoices settle through its payment providers. For Solana you send the amount, wallet and reference as plain text and run this check afterwards.

### Why match on a memo and not on the amount alone?

Two buyers can pay the same amount within minutes, and the memo is how you tell their transfers apart. A random reference per invoice makes each match unique.

### How often should the check run?

Once when the buyer taps Paid, and then every minute or so for open invoices. A check makes up to 10 `getTransaction` calls, and Free refills that method at 0.24 req/s, so on Free one check a minute is about the steady pace for one wallet.

### Does it work for a token such as USDC?

Not as written. A token payment changes a token account, so you would compare token balances in the transaction's meta, and the receiving token account stands in for the wallet.

## Related

- [Memo payment lookup](https://carbium.sh/library/usecase/memo-payment-lookup) (Use cases, UC0022)
- [Invoice payment tracker](https://carbium.sh/library/blockchainideas/invoice-payment-tracker) (Blockchain ideas, BI0021)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
