library / Integrations / I0056
RabbitMQ SOL transfer feed
A Node 24 relay reads each confirmed block with jsonParsed, finds every successful System Program transfer, inner ones included, and publishes sender, receiver and lamports to a RabbitMQ topic exchange. With no broker set, it prints a count for each block and three sample messages.
What counts as a SOL transfer
A SOL transfer is a move of lamports recorded by the System Program. The instruction is transfer, or transferWithSeed when the sender is an address derived from a base account and a seed. Both carry a source, a destination and a lamports amount, and one SOL is 1,000,000,000 lamports.
No subscription filter gives you every transfer. logsSubscribe on the WebSocket streams logs for all transactions or for those that mention an address, but the System Program writes no amount into its log lines, and an address filter needs the addresses first. The way to see all of them is to read each block and check each instruction.
Mainnet blocks carry no vote transactions since Alpenglow, so a block holds only user transactions. Only successful ones count: a failed transaction rolled its changes back, so the relay skips every transaction whose meta.err is set.
Walking a block in jsonParsed
getBlock with encoding set to jsonParsed and transactionDetails set to full returns each transaction with its System Program instructions already decoded. program is system, and parsed holds a type and an info object with source, destination and lamports. A raw encoding would leave you base58 instruction data to decode yourself.
Each transaction lists its top-level instructions in message.instructions and the calls they made in meta.innerInstructions. A program that pays out from a vault, a multisig or a withdrawal contract calls the System Program from inside its own instruction, so that transfer exists only as an inner instruction. Reading top-level instructions alone misses those payouts. The inner instruction tree entry shows the nesting.
| Where the transfer sits | How the relay finds it |
|---|---|
| Top-level instruction | message.instructions, program system, type transfer. |
| Call made by another program | meta.innerInstructions[].instructions, same shape. |
| Sender derived from a seed | Type transferWithSeed, same info fields. |
| Failed transaction | meta.err is set, so the whole transaction is skipped. |
The message body and routing key
Each transfer becomes one message. The body is a JSON object with slot, signature, n, from, to and lamports. n is the instruction's position among the transaction's top-level and inner instructions, so signature and n together name one transfer. lamports is a decimal string, which keeps amounts exact in any language that parses the JSON.
The routing key is sol.transfer.<from>.<to> on a topic exchange. A base58 address contains no dots, so each address is exactly one word to the broker, and the key stays far under the 255 byte limit. A consumer picks what it wants with a binding.
- sol.transfer.# receives every transfer.
- sol.transfer.<wallet>.* receives what a wallet sends.
- sol.transfer.*.<wallet> receives what a wallet is paid.
Declare a durable topic exchange named sol.transfers and a durable queue bound to it before you start. The relay declares nothing. It publishes with delivery_mode 2 and sets message_id to the signature and position, so the broker keeps the messages through a restart and a consumer can drop a repeat.
Publishing goes through the RabbitMQ management plugin's HTTP API, POST /api/exchanges/{vhost}/{exchange}/publish, so the file needs no AMQP client. Set RABBIT_URL to the management address, for example http://user:[email protected]:15672. The reply says whether any queue received the message, and the relay counts the ones that no queue took.
The relay
Install @solana/[email protected] and run the file with Node 24, which strips the types on load. CARBIUM_KEY is required and goes out in the x-api-key header on every RPC call. CARBIUM_RPC_URL, RABBIT_URL, RABBIT_VHOST and RABBIT_EXCHANGE are optional.
// I0056 · RabbitMQ SOL transfer feed// https://carbium.sh/library/integrate/rabbitmq-sol-transfer-feed// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { 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 sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));// RabbitMQ publish goes through the management plugin's HTTP API; unset means print only.const broker = process.env.RABBIT_URL ? new URL(process.env.RABBIT_URL) : null;const api = broker && { url: `${broker.origin}/api/exchanges/${encodeURIComponent(process.env.RABBIT_VHOST ?? "/")}/${process.env.RABBIT_EXCHANGE ?? "sol.transfers"}/publish`, auth: "Basic " + Buffer.from(`${decodeURIComponent(broker.username)}:${decodeURIComponent(broker.password)}`).toString("base64"),};type Ix = { program?: string; parsed?: string | { type: string; info: Record<string, unknown> } };type Tx = { transaction: { signatures: string[]; message: { instructions: Ix[] } }; meta: { err: unknown; innerInstructions?: { instructions: Ix[] }[] } | null };type Transfer = { slot: number; signature: string; n: number; from: string; to: string; lamports: string };async function publish(a: NonNullable<typeof api>, m: Transfer) { const res = await fetch(a.url, { method: "POST", headers: { authorization: a.auth, "content-type": "application/json" }, body: JSON.stringify({ properties: { delivery_mode: 2, message_id: `${m.signature}:${m.n}` }, routing_key: `sol.transfer.${m.from}.${m.to}`, payload: JSON.stringify(m), payload_encoding: "string" }), }); if (!res.ok) throw new Error(`rabbit ${res.status}`); return ((await res.json()) as { routed: boolean }).routed;}// null is a skipped slot; undefined is a block that could not be read after four tries.async function fetchBlock(slot: bigint) { for (let i = 0; i < 4; i++) { try { const config = { commitment: "confirmed", encoding: "jsonParsed", transactionDetails: "full", rewards: false, maxSupportedTransactionVersion: 1 } as const; return (await rpc.getBlock(slot, config).send()) as unknown as { transactions: Tx[] } | null; } catch (e) { const code = (e as { context?: { __code?: number } }).context?.__code; if (code === -32007 || code === -32009) return null; // the leader never produced this slot if (i === 3) console.error(`slot ${slot}:`, e instanceof Error ? e.message : e); await sleep(300); } } return undefined;}let first = true;async function relay(slot: bigint) { const block = await fetchBlock(slot); if (block === undefined) return true; // unreadable: keep the cursor, the next pass reads this slot again if (!block) return console.log(`slot ${slot}: skipped`); const found: Transfer[] = []; for (const t of block.transactions) { if (!t.meta || t.meta.err) continue; // a failed transaction moved nothing const all = [...t.transaction.message.instructions, ...(t.meta.innerInstructions ?? []).flatMap((g) => g.instructions)]; all.forEach((ix, n) => { const p = ix.parsed; if (ix.program !== "system" || typeof p !== "object" || !p.type.startsWith("transfer")) return; found.push({ slot: Number(slot), signature: t.transaction.signatures[0], n, from: String(p.info.source), to: String(p.info.destination), lamports: String(p.info.lamports) }); }); } console.log(`slot ${slot}: ${found.length} transfers in ${block.transactions.length} transactions`); if (!api) { if (first) found.slice(0, 3).forEach((m) => console.log(`sol.transfer.${m.from}.${m.to}`, JSON.stringify(m))); if (found.length) first = false; return; } const sent = await Promise.allSettled(found.map((m) => publish(api, m))); const failed = sent.filter((s): s is PromiseRejectedResult => s.status === "rejected"); const unrouted = sent.filter((s) => s.status === "fulfilled" && !s.value).length; console.log(` published ${sent.length - failed.length}, unrouted ${unrouted}, failed ${failed.length}`); if (failed[0]) console.error(" first failure:", String(failed[0].reason));}let next = await rpc.getSlot({ commitment: "confirmed" }).send();for (;;) { try { const tip = await rpc.getSlot({ commitment: "confirmed" }).send(); while (next <= tip) { if (await relay(next)) break; next++; } } catch (e) { console.error("loop:", e instanceof Error ? e.message : e); } await sleep(250);}
run: node main.ts
With RABBIT_URL unset the relay publishes nothing. Each block prints a line with its slot, its transfer count and its transaction count, and the first block that holds transfers also prints up to three messages with signature, sender, receiver and lamports, which checks the whole read before a broker exists.
Following the tip slot by slot
The loop asks getSlot for the newest confirmed slot, reads every block from its cursor up to that slot in order, and sleeps 250 ms. The cursor starts at the newest slot itself, so the feed carries no backlog and the first block arrives after three calls: two getSlot and one getBlock. A slot lasts about 200 ms, so a new block comes roughly five times a second and most polls find one or two new slots. Both calls ask for confirmed in the code.
Not every slot has a block. When a leader never produced its slot, getBlock answers -32007, or -32009 when the lookup reached long term storage. The relay takes either as a skipped slot, prints it and moves to the next one. Any other error gets up to four tries 300 ms apart, because the node that answers may not hold a block that just confirmed yet. If the fourth try fails too, the relay prints the slot and the error, leaves the cursor on that slot and ends the pass, so the next pass reads the same slot again.
Where it ends
- SPL tokens are out. A token transfer moves tokens between token accounts through the Token Program and lists the token accounts and the sender's authority, never the receiving wallet, so it needs its own reader.
- Lamports can move with no transfer instruction. createAccount, createAccountWithSeed and withdrawFromNonce carry a lamports amount under other type names and are skipped, and a program that debits an account it owns, or a closed account that returns its balance, adds no transfer at all. Compare meta.preBalances and meta.postBalances per transaction to catch those; the relay does not.
- One HTTP request per message is light work for a quiet block and a lot for a busy one. The messages of a block go out together, and a broker that lags shows up as failures in the log. For steady volume, replace publish with an AMQP client.
- Block reads go one at a time. When a read plus its publishes takes longer than a slot, or the plan's rate is under about five getBlock calls a second, the cursor falls further behind the tip, and nothing in the log shows that lag.
- A failed publish is printed and not retried, and the cursor lives in memory, so a restart resumes at the newest slot. A consumer that needs every transfer reads the missed slots with getBlock, or one wallet's gap with getSignaturesForAddress, which reaches back 30 days at most.
- The gRPC stream is the heavier route. It sits at https://services.carbium.sh:9443, takes the key in an x-token header and opens on Dev, Business and Pro; Free plans have no stream. It filters on the server and removes the polling, and it needs a gRPC client and the proto file, which is a larger build than this one file.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every block read logs a -32015 error and no transfers arrive. | The getBlock call has maxSupportedTransactionVersion absent or 0. Set it to 1. |
| Blocks read fine but every one shows 0 transfers. | The encoding is not jsonParsed, so instructions arrive undecoded and none carries a parsed field. Set encoding to jsonParsed. |
| The log shows rabbit 401 on every publish. | The user or password in RABBIT_URL is wrong. A 403 means the user lacks write permission on the vhost. Check both against the management login. |
| A publish fails with rabbit 404, or the connection is refused. | The management plugin is not enabled on that host and port (15672 is its default), or the vhost or exchange name is wrong. Enable rabbitmq_management and check RABBIT_VHOST and RABBIT_EXCHANGE. |
| The unrouted count equals the transfer count on every block. | The exchange exists but no queue is bound to it with a matching key. Bind a durable queue with sol.transfer.#. |
| The log shows 429 errors from the RPC calls. | A call past its rate gets 429 with a retry-after hint. Each block read tries four times, and a read that still fails leaves the cursor on its slot, so the next pass reads that slot again and the block is not dropped. Polling less often cuts only the getSlot calls, and the relay still reads about five blocks a second, so the plan's rate has to cover those getBlock calls plus the getSlot polls. |
Questions
Can a subscription filter give me all transfers?
A filter names an address or a program, and the all-logs subscription carries no amount for System Program transfers. Reading whole blocks is how you get sender, receiver and amount for every transfer.
Does it catch SPL token transfers?
No. A token transfer lists token accounts and the sender's authority, never the receiving wallet, and its amount is in token units. It needs a separate reader.
Do I need a RabbitMQ broker to try it?
No. With RABBIT_URL unset, the relay prints the transfer count for each block and up to three messages from the first block that has transfers.
Why read blocks at confirmed?
The code asks for confirmed on getSlot and getBlock, which gets each block out as soon as it is voted on. Finalized sits only 0 to 1 slots behind, so a consumer that needs finality loses almost nothing by switching both calls to finalized.
How do I get one wallet's transfers only?
Bind a queue to sol.transfer.<wallet>.* and another to sol.transfer.*.<wallet>. The relay still reads every block, and the broker does the filtering.