library / Blockchain ideas / BI0047
Stablecoin depeg monitor
A Node script that asks for executable USDC to USDT and USDT to USDC quotes at two sizes, removes the 5 bps router fee, and prints each direction's deviation from 1.00 in basis points with an OK or DRIFT verdict.
Why reserve ratios mislead
A treasury or payments team that holds USDC and USDT wants to hear when the two stop exchanging one for one. The first idea is to read a pool's two vault balances and divide them.
On a stable-swap pool that ratio tells you little. The curve is built to hold its price close to 1.00 while the reserves lean to one side, so a pool that is 70 percent USDC can still pay out within a basis point of one. A concentrated-liquidity pool has no single reserve ratio at all. Reading reserves also means writing the curve maths for each pool type and choosing which pools to read, and a real swap may split across several of them.
A routed quote skips that work. You name the input mint, the output mint and an amount, and the router returns what would come back for that amount through the pools it would use. The question a holder cares about is how much USDT arrives for this much USDC, and a quote answers it directly.
The quote as the price at size
Carbium answers quote on the same endpoint as plain RPC, https://services.carbium.sh, as one of four methods: quote, swap, health and prices. The key goes in the x-api-key header and needs the QUOTE scope. Quotes are a read, so the script holds no keypair and signs nothing.
A pool quotes a different rate for a small amount than for a large one, because a large swap moves along the curve. The script therefore asks at two sizes, 1,000 and 25,000 tokens, and reports each. Both mints have 6 decimals, so the ratio of output base units to input base units is already the rate in tokens.
| Reading | Taken from | What it tells you |
|---|---|---|
| Received rate | output amount divided by input amount | What a holder gets for each token sent, fee included |
| Before-fee rate | received rate with the router fee added back | The route's own rate, comparable to 1.00 |
| Deviation | (rate minus 1) times 10,000 | Distance from one for one, in basis points |
| Round trip | USDC to USDT before-fee rate times USDT to USDC before-fee rate | What a full circle at one size costs |
Run it with node main.ts and a key in CARBIUM_KEY. It takes no argument. It sends four quotes, one prices call and one getSlot at confirmed commitment, all at once, and settles each, so one refused call prints its reason while the others still report. The threshold comes from DRIFT_BPS and is 10 when unset.
// BI0047 · Stablecoin depeg monitor// https://carbium.sh/library/blockchainideas/stablecoin-depeg-monitor// 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 to your Carbium API key."); process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const USDT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB";const SIZES = [1_000, 25_000]; // whole tokens; both mints have 6 decimalsconst LIMIT_BPS = Number(process.env.DRIFT_BPS ?? 10);const FEE = 0.0005; // the 5 bps router fee, charged on chainconst bps = (rate: number) => (rate - 1) * 10_000;type Json = Record<string, unknown>;async function call(method: string, params: unknown[]): Promise<Json> { const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-api-key": key as string }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), }); const body = (await res.json().catch(() => ({}))) as { result?: Json; error?: { code: number; message: string } }; if (body.error) throw new Error(`${method} ${body.error.code} ${body.error.message}`); if (!res.ok || !body.result) throw new Error(`${method} HTTP ${res.status}`); return body.result;}type Leg = [src: string, dst: string, size: number];const legs: Leg[] = SIZES.flatMap((s): Leg[] => [[USDC, USDT, s], [USDT, USDC, s]]);const [[slot, prices], quotes] = await Promise.all([ Promise.allSettled([rpc.getSlot({ commitment: "confirmed" }).send(), call("prices", [])]), Promise.allSettled( legs.map(([src_mint, dst_mint, size]) => call("quote", [{ src_mint, dst_mint, amount_in: size * 1e6, slippage_bps: 50 }])), ),]);const rows = prices.status === "fulfilled" && Array.isArray(prices.value.rows) ? (prices.value.rows as unknown[][]) : [];const usd = (mint: string) => rows.find((r) => r[0] === mint)?.[1] ?? "n/a";if (prices.status === "rejected") console.error(`prices failed: ${prices.reason}`);console.log(`slot ${slot.status === "fulfilled" ? slot.value : "n/a"} listed USD: USDC ${usd(USDC)}, USDT ${usd(USDT)}`);const got = new Map<string, number>();quotes.forEach((q, i) => { const [src, , size] = legs[i]; const name = src === USDC ? "USDC>USDT" : "USDT>USDC"; if (q.status === "rejected") return console.error(`${name} ${size}: ${q.reason}`); const out = Number(q.value.destAmountOut); if (!(out > 0)) return console.error(`${name} ${size}: no output amount in the quote`); const received = out / (size * 1e6); const before = received / (1 - FEE); const drift = Math.abs(bps(before)) > LIMIT_BPS; got.set(`${name} ${size}`, before); console.log( `${name} ${size}: received ${received.toFixed(6)} (${bps(received).toFixed(1)} bps), before fee ${before.toFixed(6)} (${bps(before).toFixed(1)} bps) ${drift ? "DRIFT" : "OK"}`, );});for (const size of SIZES) { const a = got.get(`USDC>USDT ${size}`); const b = got.get(`USDT>USDC ${size}`); if (a && b) console.log(`${size} round trip: ${bps(a * b).toFixed(1)} bps`);}if (got.size === 0) console.log("NO DATA: every quote failed");
run: node main.ts
The prices call adds the listed USD figure for each mint to the first output line. That gives a second view beside the quotes and costs nothing in credits.
Both directions and the spread between them
One direction cannot tell a drift from the cost of crossing a pool. If USDC weakens against USDT, the USDC to USDT leg returns less than one USDT per USDC and the USDT to USDC leg returns more than one USDC per USDT. The two deviations carry opposite signs. When both legs fall below one together, the cause is depth and fees. The round trip shows that cost in a single number.
The script quotes each direction at the same nominal size and prints the round trip per size. A round trip near zero means the legs mirror each other. A round trip far below zero at the large size and not at the small size says the pools are thin at that amount.
Taking the 5 bps router fee out
A quote's router fee is 5 bps, charged on chain in the transaction. Every received rate therefore sits 5 bps under the route's own rate, in both directions. Left in, the fee makes a healthy pair read as 5 bps off and eats half of a 10 bps threshold.
The script divides the received rate by 0.9995 to get the before-fee rate and judges that one. A received rate of 0.9993 reads as minus 7 bps. Divided by 0.9995 it is 0.9998, minus 2 bps, which is inside the threshold. Both numbers print, so you see what a holder receives and what the pools say.
Thresholds and repeat checks before alerting
A drift line needs a rule that keeps a single odd reading from paging anyone. A workable starting point:
- Judge the before-fee deviation against a limit in basis points. Start at 10 and tune it from a week of readings of your own pair.
- Treat a size as drifting only when its USDC to USDT leg and its USDT to USDC leg lean the opposite way from one another.
- Run the script once a minute from a scheduler and alert after three DRIFT lines in a row. One reading can be a thin route, and three in a row means the pools moved.
- Alert on the large size first. It shows depth trouble earlier, and the small size shows whether the whole pair has moved.
Each run is four quotes, one prices call and one getSlot. The Free quote plan allows 10 quotes per second, so one run uses well under a second of that budget. Limits are per account, so other keys on the account draw from the same allowance. The quote plane spends no credits, and getSlot is a cheap cached read at 1 cell.
For the payments side of the same pair, Stablecoin settlement checks confirms that a transfer landed in the amount expected.
Where it ends
- A quote shows one router's view. A venue the router does not use can price the pair differently.
- Size matters. The script reads two sizes. A treasury moving a larger amount should add that size to the list.
- A quote is no settlement. State moves between the quote and any transaction, and swap only builds an unsigned transaction that you sign and send.
- A pair with both mints falling together reads normal. The deviation is between USDC and USDT, so a move of both against the dollar shows up only in the listed USD figures.
- The script keeps no history. Repeat checks need a scheduler and a place to count consecutive lines.
- A DRIFT line reports a measurement. What to do about it is a decision for your team.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every quote fails with 401 and -32001. | The key is missing the QUOTE scope. Give the key that scope in your account and send the whole key. An unknown key gets 401 at the door instead. |
| Quotes fail with 429 and a retry-after hint. | The account is over its quote rate, often because other keys share it. Run the script less often. The next scheduled run is the retry. |
| One size prints DRIFT and the other prints OK. | The pools are thin at the larger amount. Compare the round trip for that size. If it is far below zero, the deviation comes from thin pools at that amount. |
| A leg prints a failure and the round trip line for that size is missing. | The quote for that leg returned an error, and its text is on the line. The other legs still report. Check the mints and the amount, then run again. |
| The USD price part of the first line shows n/a. | The prices call failed or its answer had no row for that mint. The quote lines do not depend on it, so the verdicts stand. |
| The script prints -32601. | The method name is wrong or the method is not served. Do not retry. Check that the call says quote or prices. |
Questions
Why not read the pool's reserves and compute the rate?
A stable-swap curve keeps its rate near one across a wide range of reserves, so the balance ratio can look lopsided while the price is fine. A quote gives the rate for an amount that has been routed through real pools.
Which direction shows a depeg?
Both do, with opposite signs. If one stablecoin weakens, the leg that sells it returns less than one and the leg that buys it returns more than one. Two legs on the same side of one point to fees and depth.
Why does a healthy pair show about minus 5 bps in the received rate?
The 5 bps router fee is charged on chain in the transaction, so the received rate carries it. The before-fee line removes it, and that is the line the verdict uses.
Does the check cost credits or move funds?
It moves nothing, because a quote is a read with no signature. The quote plane spends no credits, and the getSlot call is a 1-cell cached read.
Can I watch another stablecoin pair?
Change the two mint constants and make sure both have 6 decimals, since the script treats base units as tokens. For other decimals, scale each side before you divide.