library / How to use Solana / HS0042
Swap slippage settings
One TypeScript file turns a pair's price drift and the time your swap waits to land into a slippage tolerance in basis points, measures slot time on Carbium, and prints the minimum output to accept. You set it once per pair.
What slippage guards against
A swap quote is a price at one instant. Your transaction lands some slots later, against pool balances that may have moved in between. Slippage tolerance is the shortfall you accept between the quoted output and what the pool pays when the transaction runs. If the pool pays less, the transaction fails and only the network fee is spent.
Both ends of the setting cost something. A value that is too tight turns ordinary price movement into failed transactions, and you resend into a market that keeps moving. A value that is too loose lets a poor fill go through without a complaint. Most people settle it by trial on each swap, which is the slow way. A fixed rule is faster, and it fits in a few lines.
| Setting | What you see |
|---|---|
| Tolerance below the real drift | Swaps fail with a slippage error at the pool, and each failure costs a fee and a retry. |
| Tolerance well above the drift | Swaps land, and the fill can be worse than the market justified. |
| Tolerance sized to the window | Most swaps land, and the worst fill stays inside a number you chose in advance. |
A rule that replaces guessing
Price drifts with time, so size the tolerance by time. The rule has three inputs: how fast the pair moves, how old the quote is when you send, and how many slots the transaction waits to land. Multiply the move per second by the seconds in that window, round up, and clamp the result between a floor and a cap.
- Move: the price change of the pair in basis points per second. Take two quotes of the pair a few seconds apart, divide the change by the seconds between them, and keep the largest of a handful. Store it per pair and reuse it.
- Quote age: seconds from the quote reply to the moment you send. A swap built right after its quote is about one second.
- Landing slots: slots between sending and the swap running. Three is a sensible start, and a congested moment needs more.
- Floor and cap: the file uses 10 and 300 bps. The floor keeps a calm pair from rounding to zero. The cap stops a wild input from approving a bad fill.
Slot time comes from the node. Since the Alpenglow switch a slot is about 200 ms, and the file measures it from recent performance samples so the rule follows the cluster if that changes.
The file
Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types. It takes the expected output amount in base units, the move in basis points per second and, optionally, the landing slots and the quote age in seconds. It prints the tolerance in basis points and the minimum output, the figure to check a built swap's floor against. It is read-only: it requests no quote, signs nothing and sends nothing.
// HS0042 · Swap slippage settings// https://carbium.sh/library/howsolana/swap-slippage-settings// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Slippage picker. Run: CARBIUM_KEY=... node main.ts <output base units> <move bps per second> [landing slots] [quote age seconds]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 rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const FLOOR_BPS = 10;const CAP_BPS = 300;const [outArg, moveArg, slotsArg, ageArg] = process.argv.slice(2);const moveBps = Number(moveArg);const landingSlots = Number(slotsArg ?? 3);const quoteAge = Number(ageArg ?? 1);if (!/^\d+$/.test(outArg ?? "") || !(moveBps >= 0) || !(landingSlots >= 0) || !(quoteAge >= 0)) { console.error("Usage: node main.ts <output base units> <move bps per second> [landing slots] [quote age seconds]"); process.exit(1);}const expectedOut = BigInt(outArg);// Both reads go out together; each one is settled on its own.const [samples, slot] = await Promise.allSettled([ rpc.getRecentPerformanceSamples(5).send(), rpc.getSlot({ commitment: "confirmed" }).send(),]);let slotSecs = 0.2;let source = "assumed";if (samples.status === "rejected") { console.error(`getRecentPerformanceSamples failed: ${samples.reason}`);} else { const secs = samples.value.reduce((sum, s) => sum + Number(s.samplePeriodSecs), 0); const slots = samples.value.reduce((sum, s) => sum + Number(s.numSlots), 0); if (slots > 0) { slotSecs = secs / slots; source = `measured over ${samples.value.length} samples`; }}if (slot.status === "rejected") console.error(`getSlot failed: ${slot.reason}`);const bpsFor = (slots: number) => Math.min(CAP_BPS, Math.max(FLOOR_BPS, Math.ceil(moveBps * (quoteAge + slots * slotSecs))));const minOut = (bps: number) => (expectedOut * BigInt(10000 - bps)) / BigInt(10000);console.log(`confirmed slot ${slot.status === "fulfilled" ? slot.value : "failed"}, slot time ${slotSecs.toFixed(3)} s (${source})`);console.log(`inputs: output ${expectedOut}, move ${moveBps} bps/s, quote age ${quoteAge} s`);for (const slots of [landingSlots, ...[2, 8, 16].filter((s) => s !== landingSlots)]) { const bps = bpsFor(slots); const tag = slots === landingSlots ? "chosen" : "if slow"; console.log(`${tag.padEnd(7)} landing in ${String(slots).padStart(2)} slots: slippage ${bps} bps, minimum out ${minOut(bps)}`);}
run: node main.ts <output base units> <move bps per second> [landing slots] [quote age seconds]
The two reads go out together and each is settled on its own. A failed sample read prints its error, and the file falls back to 0.2 s per slot, labelled as assumed. The minimum output is integer math on bigint, so an amount with nine decimals never passes through a float.
After the chosen setting, the file prints the tolerance for 2, 8 and 16 landing slots, so you can see how fast the window widens when sends are slow.
Reading the output
The first line shows the confirmed slot and the measured slot time. The second shows the inputs the file used. Then comes one line per landing time, each with the tolerance in basis points and the minimum output in base units.
Take a move of 8 bps per second, a one second quote age and a slot time of exactly 200 ms. Three slots give a window of 1.6 s and a tolerance of 13 bps, so an expected output of 250000000 has a minimum of 249675000. Sixteen slots give 4.2 s and 34 bps. The tolerance climbs with the window, and the floor holds a still pair at 10.
Putting the number on a Carbium quote
Quotes answer on the RPC endpoint, https://services.carbium.sh, as JSON-RPC through four methods: quote, swap, health and prices. The swap method builds an unsigned transaction that you sign and send through any RPC. Before you sign it, compare the output floor of that transaction with the minimum output this file printed.
The quote plan sets the call rate for each account, from 10 quotes per second on Free to 500 on Elite. Quote calls spend no credits, since the plan is the meter. A quote needs a key with the QUOTE scope. getSlot is a cheap cached read at 1 cell a call.
The router fee, platformFee, is 5 bps and is charged on chain inside the transaction. Keep it in view when you compare the quoted output with what lands, and read the landed swap back with the Swap transaction decoder to see the legs. For the commitment of the reads around a send, see Solana commitment levels.
Where it ends
- The rule sizes the tolerance for drift over time. It cannot see a thin pool where your own size moves the price. Judge how much your size moves the pool before you size the swap.
- The move input is yours. A number measured in a quiet hour understates a busy one, so refresh it for the pairs that matter.
- The file reads slot time from a few recent samples, so one run can sit a little off the average.
- A tolerance that bounds a bad fill does not make the fill good. The cap of 300 bps still lets a swap lose 3% and land.
- The file never calls quote or swap. It gives the tolerance and the minimum output, and the swap that uses them is yours to build.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The file prints a usage line and exits. | Pass the expected output as a whole number in base units and the move as a plain number of basis points per second, for example node main.ts 250000000 8. |
| The file stops with Set CARBIUM_KEY to your Carbium API key. | Export CARBIUM_KEY in the shell that runs node main.ts. The file reads it from the environment and never prints it. |
| The first line says the slot time is assumed. | The sample read failed (its error printed above) or came back empty. Run again. The 0.2 s fallback keeps the tolerance usable in the meantime. |
| A quote call answers 401 with -32001. | The key lacks the QUOTE scope or was cut short. Give the key the QUOTE scope and send the whole key. |
| Swaps still fail with a slippage error at the pool. | Re-measure the move for that pair and raise the landing slots. If the quote is old by the time you send, build the swap right after the quote so the window shrinks. |
| Every line sits at the 300 bps cap. | The move input is probably in the wrong unit, per minute where the file wants per second, or the window is long. Re-measure with two quotes a few seconds apart. |
Questions
Is there one slippage value that works for every pair?
No. Pairs move at different speeds, so one value is too tight for a volatile pair and too loose for a calm one. Keep one move number per pair and let the rule turn it into a tolerance.
Why measure slot time instead of using a fixed 400 ms?
A 400 ms figure doubles the landing part of the window and loosens the tolerance for no reason: at three slots and a one second quote age, 1.6 s becomes 2.2 s. The file reads recent samples and follows the cluster.
Does a higher tolerance make my swap land faster?
No. It widens the range of fills the pool may accept. How fast the transaction lands depends on how and when you send it.
Do quotes spend credits?
The quote plane spends none, because the quote plan is the meter. Free allows 10 quotes per second per account.