services
Get a key

library / How to use Solana / HS0043

Swap route breakdown

One TypeScript file asks the quote method for the same pair at three input sizes and prints each route leg by leg, so you can see which pools a swap crosses and how that changes with size. It signs and sends nothing.

By Carbium · Swap API · HS0043 · updated 2026-11-22

01

What a route breakdown answers

A quote gives you one number, the amount you receive. A route breakdown gives you the reason for it: which pools the swap crosses, in what order, and how the input is split when more than one path is used. When two quotes for the same pair disagree, the breakdown is where you look.

No dex has the best routing in general. Pool depth moves by the hour, and a path that wins at 1 SOL can lose at 100 SOL because the same pool runs out of depth. What you can do is ask for the route at the sizes you care about and read what the router picked.

The call is the quote method on the RPC endpoint. It is read-only: it returns a route and an expected output and builds nothing. The separate swap method builds an unsigned transaction that you sign and send through any RPC, and this file never calls it.

02

The code

Export CARBIUM_KEY and run the file with Node 24, which strips TypeScript types on its own. With no arguments it quotes SOL to USDC at 1, 10 and 100 SOL. Pass two mints and then your own amounts in base units to quote another pair or size. quote is a JSON-RPC method outside the standard Solana set, so the file posts it with the global fetch and leaves @solana/kit out.

main.ts
// HS0043 · Swap route breakdown// https://carbium.sh/library/howsolana/swap-route-breakdown// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITconst key: string = 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 SOL = "So11111111111111111111111111111111111111112";const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";// Usage: node main.ts [src_mint dst_mint amount_in_base_units...]const [src = SOL, dst = USDC, ...amounts] = process.argv.slice(2);const sizes = amounts.length ? amounts : ["1000000000", "10000000000", "100000000000"]; // 1, 10, 100 SOLasync function quote(amount: string): Promise<any> {  const res = await fetch(url, {    method: "POST",    headers: { "content-type": "application/json", "x-api-key": key },    body: JSON.stringify({      jsonrpc: "2.0",      id: 1,      method: "quote",      params: { src_mint: src, dst_mint: dst, amount_in: amount, slippage_bps: 50 },    }),  });  const body: any = await res.json().catch(() => ({}));  if (body.error) throw new Error(`${body.error.code} ${body.error.message}`);  if (!res.ok) throw new Error(`HTTP ${res.status}`);  return body.result;}// The first array of objects under a key that looks like a route, plan, hop or leg.function legsOf(node: any): any[] | undefined {  if (!node || typeof node !== "object") return undefined;  for (const [k, v] of Object.entries(node)) {    if (Array.isArray(v) && v.length && typeof v[0] === "object" && /route|plan|hop|leg/i.test(k)) return v;  }  for (const v of Object.values(node)) {    const found = legsOf(v);    if (found) return found;  }  return undefined;}// Plain values of one leg, with one level of nesting folded in as key.sub=value.const flat = (o: any): string =>  Object.entries(o)    .flatMap(([k, v]) =>      v && typeof v === "object"        ? Object.entries(v).filter(([, x]) => typeof x !== "object").map(([a, x]) => `${k}.${a}=${x}`)        : [`${k}=${v}`],    )    .join(" ");const results = await Promise.allSettled(sizes.map(quote));results.forEach((r, i) => {  console.log(`\nin ${sizes[i]} base units of ${src}`);  if (r.status === "rejected") {    console.log(`  failed: ${r.reason.message}`);    return;  }  const out = Object.entries(r.value ?? {}).find(([k, v]) => /out/i.test(k) && typeof v !== "object");  console.log(`  ${out ? out.join(" = ") : "no output field found"}`);  const legs = legsOf(r.value);  if (!legs) console.log("  no route array found:", JSON.stringify(r.value).slice(0, 300));  else legs.forEach((leg, n) => console.log(`  leg ${n + 1}: ${flat(leg)}`));});

run: node main.ts [src_mint dst_mint amount...]

Three quotes go out at once through Promise.allSettled, so one failing size does not hide the other two. The leg finder takes the first array of objects whose key name looks like a route, plan, hop or leg, and prints the plain values of each entry. If it finds no such array it prints the start of the raw answer, which is the quickest way to see the shape your own parser has to handle.

Amounts are integer base units as strings: lamports for SOL, which has 9 decimals, and millionths for USDC, which has 6. Keep them as strings or bigint in your own code, because a JavaScript number holds integers exactly only up to 2^53, which is about 9 million SOL in lamports. A float loses digits past 2^53 base units, and tokens with a large supply and 9 decimals reach that.

03

Reading the legs

Each printed leg is one hop of the path.

Part of a legWhat it tells you
Venue or programThe pool or program that fills the hop, printed as swapInfo.label and swapInfo.ammKey. Two sizes that use different venues show where the router changed its mind.
Input and output mintWhere the path passes through. A SOL to USDC quote that goes through a third mint adds a hop and a second pool's fee.
Share of inputThe percent field. When one hop appears twice, each leg takes a share of the input. A split is how a router uses two pools when one is too shallow for the full amount.
Output amountA leg's swapInfo.outAmount is that leg's share only, and swapInfo.inAmount is the input it received. The whole-route total is the top-level output field the file prints above the legs. Divide that total by the input at each size, adjusted for the decimals of both mints, to get the rate you would actually see.

The router fee is not part of a leg and the file does not print it. It is the quote's platformFee, 5 bps (0.05%), charged on chain in the transaction.

Compare the three sizes line by line. A single leg at 1 SOL that becomes two or three legs at 100 SOL tells you the pools the router prefers are thin. A rate that falls steadily with size is ordinary price impact. A rate that rises again at the largest size can come from a split the middle size did not use, or from fresh depth, because pools also move between the three calls.

04

On Carbium

Quotes answer on https://services.carbium.sh, the same endpoint as RPC, under four methods: quote, swap, health and prices. The key goes in the x-api-key header, as in the file. The key needs the QUOTE scope, and the quote plane spends no credits, because its plan is the meter.

Quote plans are per account: Free at $0 and 10 quotes a second, Starter at $7 and 50 a second, Pro at $28 and 150 a second, Elite at $104 and 500 a second. This file sends three quotes at once, so Free covers it. A job that sweeps many pairs or sizes needs a pause between batches or a higher plan.

Because a quote costs no credits, a scheduled run of the same breakdown spends only quote rate. Keep the results to see how routes change over a day: store the venue list and the rate per size, and diff them between runs.

Once you have settled on a route you want to take, the swap method returns an unsigned transaction for it. You sign it yourself and send it through any RPC, which keeps the signer on your side of the wire.

05

Where it ends

A breakdown is a snapshot. Between the quote and a landed transaction the pools move, so the route you read can differ from the one that executes, and the amount you receive can differ from the amount quoted. Slippage tolerance is the guard for that, and the file sends slippage_bps: 50 (0.5%) with each quote. The only proof of what a swap delivered is the landed transaction read back with getTransaction.

The file shows the routes Carbium's router chose. It does not rank dexes against one another, and it cannot say which venue would have beaten the router, because it never quotes a venue directly. Treat a venue name in the output as the router's choice for that size at that moment.

The leg finder is a heuristic. It reads key names and plain values and knows nothing about the answer's schema, so it will print an unfamiliar field as it finds it and will not label it. Once you know the shape you need, replace it with a typed read of the fields you use.

Three sizes of one pair say little about a market. Add the pairs and sizes your users actually swap before you draw a conclusion about routing.

06

When it goes wrong

what goes wrongwhat to do
Every size prints failed with code -32001.The key is unknown or has no QUOTE scope, and the call came back as a 401. Send the whole key and give it the QUOTE scope in your account.
The answer is an error with code -32601.The method name is wrong or not served. Do not retry. The quote methods are quote, swap, health and prices.
One size prints a failed: line with the error's code and message instead of a route.Read its message. Check that both mints are real, that the amount is an integer string in base units of the input mint, and that the pair has a pool at that size.
No route array found, and the raw answer is printed.The answer uses key names the leg finder does not match. Read the printed JSON, then point the finder at the key that holds the hops.
The output amount looks far too small.The amount was given in whole tokens, so the output is short by 10 to the power of the input mint's decimals: a billion for SOL, a million for USDC. Use base units: 1 SOL is 1000000000 lamports and 1 USDC is 1000000.
HTTP 429 on a run with many sizes.The quote rate of your plan was exceeded. Send the sizes in smaller groups with a pause between them, or move to a plan with a higher quote rate.
07

Questions

Which dex has the best swap routing on Solana?

It depends on the pair, the size and the minute. Run the breakdown at the sizes you swap and read which venues the router picks, then check them again later, because the answer moves with pool depth.

Does a quote cost credits?

No. The quote plane spends no credits and is metered by its plan, which sets how many quotes a second you can send.

Does the quote include a fee?

Yes. The router fee, platformFee, is 5 bps (0.05%) and is charged on chain in the transaction. Pool fees on each hop are part of the route's output.

How do I turn a route into a transaction?

Call the swap method. It builds an unsigned transaction that you sign and send through any RPC.