How to Plan and Price a Bitcoin Spend with GetBlock's Blockbook Add-on
DevRel
August 17, 2026
16 min read
Bitcoin has no account balances. The number your wallet shows you is a total it computes on the spot by adding up unspent transaction outputs, the UTXOs your keys control. To send a payment, a wallet cannot just subtract from a balance. It has to choose which of those outputs to spend, and that choice has real money riding on it.
The choice is also circular. The fee is a price per virtual byte, so it depends on the size of the transaction. The size depends on how many inputs the transaction has. And how many inputs it needs depends on the fee. Each answer depends on the other two.
It gets worse, because some outputs only look spendable. A mining reward is locked by consensus for 100 blocks. An output worth less than the fee it would cost to spend it is stranded value that inflates your balance without being usable. Get any of this wrong and you produce a transaction that overpays by an order of magnitude, cannot be relayed, or cannot be mined at all.
This guide shows you how to decide which unspent outputs to spend for a Bitcoin payment, and what that payment will cost, using GetBlock's Blockbook add-on. You will build the selection layer a wallet runs before it ever touches a key.
TL;DR
A Bitcoin balance is a sum of UTXOs, not a number in an account. Spending means choosing which outputs to consume, and the naive choice traps you in a loop where the fee depends on the size, the size depends on the inputs, and the inputs depend on the fee.
Effective value breaks the loop. Subtract each output's own input cost from its value up front. Once every output has already paid for its input, the target you are selecting against stops moving as you add inputs, and the leftover at the end is exactly the change.
Some outputs cannot be spent even though they show in the balance. Coinbase outputs are locked for 100 blocks by consensus, and outputs worth less than their own input cost are uneconomic at the current feerate. Both have to be filtered out before selection.
Blockbook gives you the two reads a plain node cannot. The address-indexed UTXO set for any address, and fee estimates per confirmation target, both over plain REST GET requests.
Rank plans by total cost, not by fee. A plan that keeps change looks cheaper, but that change still has to be spent one day. Charging each plan for the change it leaves behind is what makes plans comparable.
How Bitcoin coin selection actually works
Every payment you have ever received sits on-chain as one or more outputs, each locked to a script only your keys can satisfy. Your balance is just the sum of the ones you have not spent yet. When you spend, you consume whole outputs as inputs, and the transaction creates new outputs: one to the recipient, and usually one back to yourself as change.
Two costs decide everything. Each input you add makes the transaction bigger, and a bigger transaction costs more in fees. A native segwit input, for example, costs about 68 virtual bytes, so at 50 sat per virtual byte each input you spend adds roughly 3,400 satoshis to the fee. That is why a wallet full of tiny outputs is expensive to spend: the payment might be small, but paying it requires many inputs, and each input has a price.
Now the circular part. To know the fee, you need the size. To know the size, you need the input count. To know the input count, you need to know how much each input contributes after its own fee, which needs the fee. The trick that cuts the knot is a single idea: effective value. Instead of asking "how much is this output worth," ask "how much is this output worth after paying the fee to spend it." That is its value minus the cost of its own input. Once every output has prepaid its input like that, the amount you are trying to reach never changes as you add inputs, because the input costs are already baked in. The circularity is gone, and the math becomes ordinary subset selection.
Why the Blockbook add-on
A plain Bitcoin node cannot answer the one question coin selection starts from: "what are the unspent outputs for this address?" Bitcoin Core tracks outputs by transaction, not by address, so it has no address index to query. That is the gap the Blockbook add-on fills. Here is what it gives you:
The address-indexed UTXO set: A single GET request to /api/v2/utxo/{address} returns all unspent outputs for an address, along with their values, confirmations, and a coinbase flag when they are mining rewards. This is the raw material selection runs on, and it is exactly what a bare node will not give you.
Fee estimates per target: /api/v2/estimatefee/{blocks} returns the feerate for a confirmation target, so you can price the same plan for "next block" and for "within a day" and let the caller choose. A companion endpoint reports what recent blocks actually paid, so you can sanity-check the estimate against reality.
Plain REST, no key, no risk: Every call in this guide is a GET request. Nothing needs a private key, and nothing it produces can move coins. Turning a plan into a real transaction means building and signing a PSBT, which this program never does. That separation, where the part that chooses coins never has to hold a key, is worth keeping as you grow the code.
What you'll build
You will write a `planAt(spendable, { amount, satPerKvB, inputType, toType, changeType })` function that:
Converts every output to its effective value, its worth minus the fee for its own input, which removes the circularity between fee and input count.
Drops outputs that cost more to spend than they hold, and reports how much value that strands.
Searches for a changeless combination that lands just above the target, so the transaction needs no change output at all.
Falls back to largest-first and random-draw selection when no changeless combination exists.
Prices each candidate plan, dropping a change output that would be dust and handing the leftover to the miner instead.
Ranks the plans by total cost, the fee plus what the change it leaves behind will cost to spend later.
You will need Node.js 20.6 or later (for the built-in `fetch` and `--env-file`, so there is nothing to install), a free GetBlock account, and a Bitcoin endpoint with the Blockbook add-on enabled. You do not need a wallet or any funds. The guide points at a busy public address whose UTXO set is fragmented and dust-heavy, which is exactly what makes coin selection worth watching.
Setting up
Create a Bitcoin mainnet endpoint with the Blockbook add-on in the dashboard, then copy the URL exactly as it appears:
1
https://shared.eu-central-1.getblock.io/<YOUR_ACCESS_TOKEN>
Scaffold the project and set it to ES modules:
1
2
3
mkdir blockbook-utxo-planner && cd blockbook-utxo-planner
npm init --yes npm pkg set type=module
npm pkg set type=module
Put your endpoint and a target address in a .env file. Your access token lives in that URL, so keep it out of version control:
1
2
3
BLOCKBOOK_URL=https://shared.eu-central-1.getblock.io/<YOUR_ACCESS_TOKEN>
SPEND_FROM=bc1q3zcdunpmqgn8enyxa3smu7fwrfvya35dz3uvjy
SEND_TO=bc1qwzrryqr3ja8w7hnja2spmkgfdcgvqwp5swz4af4ngsjecfz0w0pqud7k38 MIN_CONFIRMATIONS=1
Building the planner
The full file is one dependency-free plan.js. Below are the pieces that carry the ideas. The complete reporting code, the fee-tier table, and the sensitivity table live in the repo.
Handle satoshis as integers, and size a transaction
Rule one of wallet code: never put a satoshi value through a floating-point number. 0.1 + 0.2 is not 0.3, and here that is somebody's money. Every amount is a BigInt count of satoshis, from the moment it is parsed to the moment it is printed:
1
2
3
4
5
6
7
8
9
10
11
12
/** Parse a decimal BTC string ("0.0015") into satoshis, without touching a float. */
function toSats(btc) {
const match = String(btc).trim().match(/^(\d*)(?:\.(\d{0,8})\d*)?$/);
if (!match) throw new Error(`not a BTC amount: ${btc}`);
const [, whole = '0', fraction = ''] = match;
return BigInt((whole || '0') + fraction.padEnd(8, '0'));
}
/** Multiply a vsize by a feerate in sat/kvB, rounding the fee up. */
function feeFor(vsize, satPerKvB) {
return (BigInt(Math.ceil(vsize)) * satPerKvB + 999n) / 1000n;
}
Sizing is a table of per-script-type costs. The reason a native segwit input is cheaper than a legacy one is the witness discount: witness data counts as a quarter of a virtual byte. That is why a `p2wpkh` input is 68 vB while a `p2pkh` input is 148, and a Taproot `p2tr` input is only 58:
1
2
3
4
5
6
7
const SCRIPTS = {
p2pkh: { input: 148, output: 34, segwit: false },
'p2sh-p2wpkh': { input: 91, output: 32, segwit: true },
p2wpkh: { input: 68, output: 31, segwit: true },
p2wsh: { input: 105, output: 43, segwit: true },
p2tr: { input: 58, output: 43, segwit: true },
};
One more sizing helper matters later: the dust threshold. An output is dust when it would cost more to spend than it holds, and the network will not relay it. Bitcoin Core prices dust at the dust relay fee, 3 sat/vB by default, over the output's own size plus the size of the input that would one day spend it:
1
2
3
function dustThreshold(type) {
return BigInt(Math.ceil((SCRIPTS[type].output + SCRIPTS[type].input) * 3));
}
Talk to Blockbook
One helper fetches and loudly fails when the path is wrong, and the other turns fee estimates into satoshis. A REST endpoint answering with HTML is Blockbook's explorer page, which means your path was wrong, not that the chain said no:
1
2
3
4
5
6
7
8
9
10
11
12
async function blockbook(path) {
const response = await fetch(`${baseUrl}${path}`);
const text = await response.text();
let body;
try {
body = JSON.parse(text);
} catch {
throw new Error(`${path} did not return JSON (HTTP ${response.status})`);
}
if (body?.error) throw new Error(`${path}: ${body.error}`);
return body;
}
Fee estimates come per confirmation target. The node only estimates over a bounded horizon, so a request outside it fails rather than guessing. Ask for several tiers at once and skip the ones that come back empty:
1
2
3
4
5
6
7
8
9
10
11
async function feeEstimates(targets) {
const settled = await Promise.allSettled(
targets.map(async (blocks) => ({
blocks,
satPerKvB: toSats((await blockbook(`/api/v2/estimatefee/${blocks}`)).result),
})),
);
return settled
.filter((entry) => entry.status === 'fulfilled' && entry.value.satPerKvB > 0n)
.map((entry) => entry.value);
}
One unit trap is worth burning into memory: `estimatefee` returns BTC per kilo-virtual-byte. A value of "0.00000490" is 490 sat/kvB, which is 0.49 sat/vB. Convert it once, in one place, and never again.
Turn value into effective value, then select
Here is the idea that makes the whole thing work. Map each output to its effective value, drop the ones that no longer clear zero, and select against a target that was computed with zero inputs:
1
2
3
4
5
6
const inputFee = feeFor(SCRIPTS[inputType].input, satPerKvB);
const candidates = spendable
.map((utxo) => ({ ...utxo, effective: utxo.value - inputFee }))
.filter((utxo) => utxo.effective > 0n)
.sort((a, b) => (b.effective > a.effective ? 1 : b.effective < a.effective ? -1 : 0));
Because each candidate has already paid for its own input, the target never moves as inputs are added, and the leftover at the end is exactly the change. Three strategies then run in effective-value terms:
Changeless search looks for a combination that lands just above the target, inside a window equal to the cost of a change output (creating one now, plus spending it later). This is the plan every wallet wants: no change output means a smaller transaction, a lower fee, no leftover dust, and no link between this payment and the next. It is a depth-first search with pruning, capped by a try budget because the space is exponential.
Largest-first takes the biggest outputs until the target is covered. Simple, but it strips the wallet of large outputs, leaving only small ones behind.
Random draw shuffles and takes until covered. It is not a worse largest-first: it fragments the wallet less, so the fee you save today is not paid back with interest the day you have to spend forty dust outputs at once. Bitcoin Core falls back to random for the same reason.
The simplest of the three shows the shape:
1
2
3
4
5
6
7
function selectLargestFirst(candidates, target) {
const indexes = []; let total = 0n;
for (let i = 0; i < candidates.length && total < target; i++) {
indexes.push(i); total += candidates[i].effective;
}
return total >= target ? { indexes, total } : null;
}
Price each plan, and rank by total cost
Selection picks the inputs. Costing decides what happens to the leftover, and it is where change either becomes a real output or gets handed to the miner as fee. If the change would fall below the dust threshold, keeping it is a mistake, so the whole leftover becomes fee instead:
1
2
3
4
5
6
7
8
9
10
const change = gross - amount - feeFor(withChange, satPerKvB);
if (change < dustThreshold(changeType)) {
const fee = gross - amount; // leftover goes to the miner
return { change: 0n, fee, totalCost: fee, /* ... */ };
}
const fee = feeFor(withChange, satPerKvB);
return {
change, fee, // charge this plan for spending its change one day, so it compares fairly totalCost: fee + feeFor(SCRIPTS[changeType].input, satPerKvB), /* ... */
};
That `totalCost` is the point. Comparing fees alone is misleading, because a changeless plan's fee has swallowed the leftover and makes the plan look expensive compared to one that keeps its change. But that change still has to be spent one day, and paying for its input then is a real cost deferred, not avoided. Charging each plan for the change it leaves behind puts both on the same footing.
Exclude what cannot be spent
The last piece is the one most people skip, and it is the difference between a valid plan and an invalid one. Two kinds of output look spendable in a balance and are not. A coinbase output is locked for 100 blocks by consensus, so spending one early does not just risk a bad plan; it produces a transaction the network rejects:
1
2
3
4
5
6
7
8
9
if (utxo.coinbase && confirmations < 100) {
immature++;
continue;
}
if (confirmations < minConf) {
tooNew++;
continue;
}
spendable.push({ txid: utxo.txid, vout: utxo.vout, value, confirmations });
The other kind, the uneconomic output, is handled by the effective-value filter above: any output worth less than the fee for its own input is dropped before selection ever sees it.
Run it and watch a wallet degrade
This is where the ideas pay off. Point the planner at the fragmented address and ask to send 0.0015 BTC:
1
node --env-file=.env plan.js 0.0015
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Blockbook Bitcoin at height 962906
Spending from bc1q3zcdunpmqgn8enyxa3smu7fwrfvya35dz3uvjy
270 unspent output(s), 0.09544355 BTC held
148 spendable, 0.02297506 BTC
122 below 1 confirmation(s)
Selection at 0.49 sat/vB, targeting 6 block(s)
strategy inputs vsize fee sats
strategy inputs vsize fee sats
change BTC total sats
changeless search 12 870 439
none 439
largest first 10 765 375
0.00013625 409
random draw 10 765 375
0.00003833 409
Best: largest first
Two facts jump out already. The address holds 0.0954 BTC, but only 0.0230 BTC of it is spendable, because 122 of its 270 outputs are still sitting in the mempool. And a 0.0015 BTC payment needs 10 inputs, because this wallet has no large outputs to draw on. At this low feerate the change is nearly free, so keeping it wins.
Now force a busy mempool and the answer flips:
1
node --env-file=.env plan.js 0.0015 --feerate 300
1
2
3
4
5
Selection at 300.00 sat/vB
148 output(s) cost more to spend than they hold at this
feerate, and are out of play
Every output is uneconomic at this feerate: 0.02297506 BTC is held here,
and none of it can move until fees fall.
The balance is real, the keys work, and not one satoshi can move, because every output is worth less than the 20,400 sats its own input would cost. Point the planner at a mining address instead and you see the other exclusion: of 226 BTC held, 77 BTC is unspendable because 28 recent mining rewards are still inside their 100-block maturity window. Consensus rejects any attempt to spend them.
Where to take it
Three changes turn this from a demo into a wallet's real selection layer:
Plan across the entire wallet, not a single address: The same `/api/v2/utxo/` path accepts an xpub, ypub, or zpub in place of a single address and returns the unspent outputs across all derived addresses, so the selection runs over the real wallet. The logic is unchanged. The change is that each chosen input must carry the derivation path its signer will need, so check which fields your endpoint returns for an xpub before relying on them.
Mix script types honestly: The sizing here assumes every input is the same type, which is true for a single address but false for a real wallet. Carry a per-input vsize instead of a single input type, and compute each input's effective value from its own cost. A Taproot input at 58 vB and a legacy input at 148 vB are worth genuinely different amounts of the same nominal value.
Turn the plan into a PSBT: The plan already specifies the outpoints, amounts, and change. A PSBT is that plus the metadata a signer needs. Building one maintains the split this guide relies on, in which the process that chooses coins never has to hold a key.
Two limits are worth knowing before you ship. The changeless search is capped at 100,000 attempts, so on a very large UTXO set, it can miss a valid combination. And every plan is a snapshot: an output can be spent by another process between your query and your broadcast, so a production wallet locks the outputs it has selected and re-checks them before signing.
Access the full guide here and the complete code repository.
Conclusion
You built a Bitcoin coin selector and fee planner in one dependency-free file, using Blockbook's UTXO and fee-estimate endpoints to answer the question a wallet has to answer before it can sign: which outputs to spend, and at what cost. The moves that made it work were switching to effective value so each input pays for its own fee and the target stops moving, excluding outputs that consensus or economics put out of reach, searching for a combination that needs no change, dropping change that would be dust, and comparing plans by total cost rather than by fee. None of it needed a private key.
To build this yourself, create a free GetBlock account, enable the Blockbook add-on on a Bitcoin endpoint, and run the planner against the fragmented address above. Then point it at your own xpub and watch it plan across your real wallet.
DevRel
August 17, 2026
16 min read
DevRel at GetBlock with over five years of experience in building and writing developer documentation.
Popular Posts
December 4, 2026
8 分鐘閱讀
September 14, 2026
4 分鐘閱讀