---
id: BI0071
title: "Swap quote freshness check"
url: https://carbium.sh/library/blockchainideas/swap-quote-freshness-check
collection: Blockchain ideas
category: Swap-powered apps
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Swap quote freshness check

A short script asks for the same SOL to USDC quote ten times, a second apart, next to the slot and the price list. You get the distinct answers, the longest unchanged run and the call time, from your own vantage point.

## What fresh means for a quote

A quote is a claim about pool state at one moment. A pool's state changes whenever a swap touches it, and since the Alpenglow switch a slot lasts about 200 ms. On a busy pair such as SOL to USDC, the amount out for a fixed input should keep moving as slots go by. A source that returns the same amount out for many slots in a row is either serving a quiet route or serving an old answer.

Freshness is the gap between that moving chain and the number in your hand. One answer cannot show it, because a single answer has nothing to be compared with. You measure it by asking the same question again and again against a clock you trust, then counting.

- Distinct answers: how many different amounts out came back across the samples.
- Longest unchanged run: the most samples in a row that returned the identical amount out while the slot kept advancing.
- Call time: milliseconds from sending the request to holding the settled answer, measured on your machine with `performance.now`.

A published benchmark states the conditions of whoever ran it. Your region, your key, your swap size and your pair are different. One run of your own takes about ten seconds and prints every sample, so the evidence is on your screen.

## The sampling loop

Each sample sends three calls at once. `quote` and `prices` are [quote-plane methods](https://carbium.sh/docs#quote) on the same `https://services.carbium.sh` endpoint as plain RPC, and `getSlot` goes through `@solana/kit` at confirmed commitment, set explicitly in the call. The quote asks for 1 SOL (1000000000 lamports) to USDC with `slippage_bps` 50. The size never changes, so every sample asks the same question.

1. Start `performance.now` before each call and stop it when the call settles, so the milliseconds include the network and the parse.
2. Run the three calls with `Promise.allSettled`. A failing call prints its reason and the sample still prints the rest.
3. Find the amount out in the quote answer: the first whole number in a field whose name starts or ends with `out`. The first sample prints that field name so you can confirm it.
4. Print the slot, the amount out, the change from the previous amount out in base units, the price that amount implies next to the `prices` number, and the three call times.
5. Wait until the next sample is due and repeat. Sample i starts i gaps after the first, so a slow call shortens the wait and never pushes later samples back. After the last sample, print the summary.

`main.ts` (run: `CARBIUM_KEY=<YOUR_KEY> node main.ts`)

```ts
// BI0071 · Swap quote freshness check
// https://carbium.sh/library/blockchainideas/swap-quote-freshness-check
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { 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 headers = { "x-api-key": key };
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers }));
const SOL = "So11111111111111111111111111111111111111112";
const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const [countArg = "10", gapArg = "1000", amount = "1000000000"] = process.argv.slice(2);
const count = Number(countArg);
const gap = Number(gapArg);
if (!Number.isInteger(count) || count < 2 || !Number.isInteger(gap) || gap < 0 || !/^[1-9]\d*$/.test(amount)) {
  console.error("Usage: node main.ts [samples >= 2 [gap-ms [amount-in-lamports]]]");
  process.exit(1);
}
async function timed<T>(run: () => Promise<T>): Promise<{ value: T; ms: number }> {
  const t = performance.now();
  const value = await run();
  return { value, ms: Math.round(performance.now() - t) };
}
async function post(method: string, params: unknown): Promise<any> {
  const res = await fetch(url, {
    method: "POST",
    headers: { ...headers, "content-type": "application/json" },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
  });
  const body: any = await res.json().catch(() => ({}));
  if (body.error) throw new Error(`${method} ${body.error.code} ${body.error.message}`);
  if (!res.ok) throw new Error(`${method} HTTP ${res.status}`);
  return body.result;
}
function outField(node: any): [string, bigint] | undefined {
  for (const [k, v] of Object.entries(node ?? {})) {
    if (/^out|out$/i.test(k) && /^\d+$/.test(String(v))) return [k, BigInt(String(v))];
    if (v && typeof v === "object") {
      const found = outField(v);
      if (found) return found;
    }
  }
  return undefined;
}
const ms = (r: PromiseSettledResult<{ ms: number }>) => (r.status === "fulfilled" ? r.value.ms : "n/a");
const outs: bigint[] = [];
const slots: bigint[] = [];
const quoteMs: number[] = [];
let prev: bigint | undefined;
const start = performance.now();
for (let i = 1; i <= count; i++) {
  const [q, p, s] = await Promise.allSettled([
    timed(() => post("quote", { src_mint: SOL, dst_mint: USDC, amount_in: amount, slippage_bps: 50 })),
    timed(() => post("prices", [])),
    timed(() => rpc.getSlot({ commitment: "confirmed" }).send()),
  ]);
  for (const r of [q, p, s]) {
    if (r.status === "rejected") console.error(`sample ${i} call failed: ${r.reason instanceof Error ? r.reason.message : r.reason}`);
  }
  const found = q.status === "fulfilled" ? outField(q.value.value) : undefined;
  if (i === 1) console.log(found ? `amount out field: ${found[0]}` : "no amount out field found in the quote answer");
  const out = found?.[1];
  const slot = s.status === "fulfilled" ? s.value.value : undefined;
  if (slot !== undefined) slots.push(slot);
  if (q.status === "fulfilled") quoteMs.push(q.value.ms);
  let change = "n/a";
  if (out !== undefined) {
    const d = prev === undefined ? undefined : out - prev;
    change = d === undefined ? "first" : `${d > 0n ? "+" : ""}${d}`;
    outs.push(out);
    prev = out;
  }
  const implied = out === undefined ? NaN : Number(out) / 1e6 / (Number(amount) / 1e9);
  const sol = p.status === "fulfilled" ? Number(p.value.value?.solUsd) : NaN;
  console.log(`#${i} slot ${slot ?? "n/a"} out ${out ?? "n/a"} change ${change} | quote ${implied.toFixed(4)} prices ${sol.toFixed(4)} USD/SOL | ms quote ${ms(q)} prices ${ms(p)} slot ${ms(s)}`);
  if (i < count) await new Promise((r) => setTimeout(r, Math.max(0, start + i * gap - performance.now())));
}
let run = 1;
let longest = outs.length ? 1 : 0;
for (let i = 1; i < outs.length; i++) {
  run = outs[i] === outs[i - 1] ? run + 1 : 1;
  longest = Math.max(longest, run);
}
const sorted = [...quoteMs].sort((a, b) => a - b);
console.log(`--- ${outs.length} of ${count} quotes answered, ${new Set(outs).size} distinct answers, longest unchanged run ${longest}`);
console.log(`--- slots ${slots.length ? `${slots[0]} to ${slots[slots.length - 1]}` : "n/a"}, ${new Set(slots).size} distinct`);
console.log(`--- quote call median ${sorted[Math.floor(sorted.length / 2)] ?? "n/a"} ms, max ${sorted[sorted.length - 1] ?? "n/a"} ms`);
```

The three arguments are the sample count (10), the gap in milliseconds (1000) and the amount in lamports (1000000000). At a one second gap and 200 ms slots, the first and last samples sit about 45 slots apart.

The request rate is small. Each sample sends two quote-plane calls, so a one second gap means two a second, well under the 10 quotes/s of the Free quote plan. `getSlot` is a [cheap cached read](https://carbium.sh/docs#rpc) admitted at 1 cell a call, and its RPC work is metered in credits. The quote plane [spends no credits](https://carbium.sh/docs#limits). Both quote-plane calls need a key with the QUOTE scope.

> The first line of the run names the field the code took as the amount out. Check that it is the amount out before you trust any number below it.

## Quote, slot and prices side by side

Every printed line puts three clocks next to each other. The slot is the chain's own clock. The amount out is the quote source's view of the pool. The `prices` number is a separate answer from the same plane, so a quote that has drifted from it shows up as a gap you can see.

| Column | Comes from | What to look for |
|---|---|---|
| slot | `getSlot` at confirmed commitment | Rises by about five a sample at a one second gap. A repeat is possible, because getSlot is a cached read. |
| out and change | the `quote` answer | Amount out in USDC base units (6 decimals). Change is the difference from the previous sample, 0 when the answer sat still. |
| quote and prices | amount out as USD per SOL, and `solUsd` from `prices` | The two should sit close. Read the size of the gap on the first run and hold later runs to it. |
| ms | `performance.now` around each call | Time from send to settled answer, as your machine sees it. |

The implied price divides the amount out by 1,000,000 for USDC's 6 decimals and scales by the amount in. It is a display number, and the comparison that counts is the integer amount out. The gap to `prices` has a floor you should read before setting a mark. A 1 SOL swap moves the pool's price by its own size, and a quote's router fee (`platformFee`) is 5 bps, charged on chain in the transaction. The fields of the answer are laid out in [Solana swap API quote](https://carbium.sh/library/howsolana/solana-swap-api-quote).

## Reading the numbers

Write the pass marks down before the first run, then run the check against the source you use today and see what its numbers say. A mark chosen after the output tends to match the output.

| Number | What it tells you | Example mark |
|---|---|---|
| Distinct answers | How often the quote moved. 1 of 10 means the amount out never changed in ten seconds. | At least 5 of 10 for 1 SOL to USDC |
| Longest unchanged run | The longest stretch the answer sat still. At a one second gap each sample in the run is about five slots. | No run past 3 samples |
| Slots advanced | Whether the clock moved during the run. If it barely did, the run says little. | About 45 across ten samples |
| Quote call median and max | What each look at the quote costs you in waiting, from your machine. | A median and a max that fit inside your own timeout |

The figures above are examples for one busy pair. A quiet pair or a large size changes what normal looks like, so set yours from a first run you trust.

Read the numbers in order. Slots advanced tells you whether the run was a fair test. Distinct answers and the longest unchanged run speak to freshness. The call time speaks to waiting. A source with many distinct answers and a long max call time suits a screen that must show a live price. A source with few distinct answers and a short call time suits a job that tolerates an older answer and cannot wait.

> Run it twice, once in a busy hour and once in a quiet one. A single run catches one moment of one market.

## Where it ends

- One pair and one size. SOL to USDC at 1 SOL says nothing about a thin pair or a large swap. Change the `SOL` and `USDC` constants and the amount argument, then rerun.
- One vantage point. Call times include your own network path and the run's start-up, so a machine in another region gets other numbers.
- A short run. Ten samples show the shape of about ten seconds. A stall that lasts a minute needs a longer run, such as 300 samples at one a second.
- The price list is Carbium's own answer, so agreement with it shows two calls consistent with each other. For an outside reference, read a pool's vault balances with `getTokenAccountBalance` and compute that pool's price yourself.
- The slot comes from the code's own `getSlot` call, sent at the same moment as the quote. It dates the sample and does not name the pool state the quote used.
- It sends no transaction. A quote that looks fresh still has to land, and only a landed swap proves the price you got.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Every quote call prints a failure line with code -32001. | The key lacks the [QUOTE scope](https://carbium.sh/docs#quote). Give the key that scope in your account and send the whole key, since an unknown key answers [401 at the door](https://carbium.sh/docs#errors). |
| The first line says no amount out field was found in the quote answer. | The answer's field names did not match the pattern. Print the raw answer, find the field that holds the amount out and change the pattern in `outField`. |
| The summary shows 1 or 2 distinct slots after a ten second run. | Treat the run as void for freshness, because the clock you measure against did not move. Rerun with a longer gap. |
| A sample prints a failed call with HTTP 429. | The account's budget is spent, often by other keys on it, since [limits are per account](https://carbium.sh/docs#limits). Lengthen the gap and rerun. The summary counts only the quotes that answered. |
| The first sample's call time is far above the rest. | The first request pays for opening the connection. Read it on its own and judge the rest, or send one warm-up call before the loop. |
| The prices column prints NaN. | The `prices` answer carried no `solUsd` field or the call failed. The failure line above the sample says which, and the rest of that sample still stands. |

## Questions

### How many samples do I need?

Ten shows the shape. For a claim about stability, run a few hundred at one a second, which is two quote-plane calls a second and stays under the 10 quotes/s of the Free quote plan.

### Why does the amount stay fixed?

A changing size changes the question, so any movement in the answer could come from the size and not from the pool. A fixed size leaves time as the only variable.

### Does the check spend credits?

The quote plane [spends no credits](https://carbium.sh/docs#limits). `getSlot` is admitted at 1 cell a call, and its RPC work is metered in credits.

### What does a long unchanged run mean?

Either the pair was quiet or the source held an old answer. One run cannot tell them apart. A second pair or size, or a pool price read yourself, can.

## Related

- [Solana swap API quote](https://carbium.sh/library/howsolana/solana-swap-api-quote) (How to use Solana, HS0007)
- [RPC latency CI gate](https://carbium.sh/library/blockchainideas/rpc-latency-ci-gate) (Blockchain ideas, BI0032)
- [carbium.sh/docs#quote](https://carbium.sh/docs#quote)
- [carbium.sh/docs#prices](https://carbium.sh/docs#prices)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
