Build a transaction from inputs and outputs
Build a transaction by hand with @bsv/sdk that spends testnet coins your own key holds, pays one output, returns the change to you and goes to the network through BSV Broadcaster. Work this way when your code holds the key and has to choose each input, output and script itself, for example a service that signs without a wallet or an app with a custom script. An app that works through the user’s wallet calls createAction on WalletClient instead, and the wallet builds the transaction. The example runs on its own in an empty folder on testnet and ends with a transaction ID that you open on the testnet explorer.
Before you begin
- Node.js 22 or newer, which
@bsv/sdkrequires. - BSV Desktop on testnet, to sign in to the testnet faucet. If you do not have it yet, follow Set up a testnet wallet.
How it works
Two scripts and three services take part:
create-key.mjscreates a testnet private key, writes it to.envand prints the address of that key.- The faucetA site that sends free test coins to an address at bsvfaucet.com pays testnet coins to that address. Its payment is the source transaction, and the output that pays your address is the one your transaction spends.
send.mjsfetches the source transaction from the WhatsOnChain testnet API, builds a transaction with one input and two outputs, computes the fee, signs it and sends it to the testnet endpoint of BSV Broadcaster.- The testnet explorer shows the transaction once BSV Broadcaster has accepted it.
Each input points at an output of an earlier transaction, and the outputs set who can spend the coins next. How transactions and fees work explains the model and how the fee is computed.
Create a key
The first step is to create a project folder and a testnet key for it:
Install the SDK
Create an empty folder, open it in the terminal and install @bsv/sdk:
npm init -y
npm install @bsv/sdkThis page was written against @bsv/sdk 4.0.1.
Keep the key out of git
Add a .gitignore file to the project folder, so the key never reaches a repository:
.env
node_modules/Generate the key
The .env file holds the private key that controls the coins at your address. Keep it private, never print it, paste it into code or commit it, and never share it. Anyone with this key can spend those coins.
Generate a private key and write it to .env. Save this script as create-key.mjs in the same folder:
import { existsSync, writeFileSync } from 'node:fs'
import { PrivateKey } from '@bsv/sdk'
if (existsSync('.env')) {
console.log('.env already exists, nothing was written.')
} else {
const key = PrivateKey.fromRandom()
writeFileSync('.env', `TESTNET_WIF=${key.toWif([0xef])}\n`, { mode: 0o600 })
console.log(`Testnet address: ${key.toAddress('testnet')}`)
}toWif([0xef])encodes the key in WIFWallet Import Format, a text encoding of a private key with the testnet prefix, and the script stores it in.envasTESTNET_WIF.toAddress('testnet')returns the testnet address of the key. With no argument, it returns a Mainnet address.- The script checks first that
.envdoes not exist, so running it again does not replace a key that already holds coins.
Run the script
Run it once:
node create-key.mjsTestnet address: mngg4eaf...dvwWyTMThe address starts with m or n, and the script never prints the key itself.
Fund the address
Funding is a step you do by hand in the browser, because the faucet asks you to sign in with a wallet before it sends free testnet coins:
Request coins from the faucet
Follow Get free testnet coins in the web app guide, and paste the address that create-key.mjs printed in Destination address, instead of the address of BSV Desktop. Request more than 1,000 satoshis, such as 1000000, since send.mjs pays 1,000 satoshis plus the fee. The faucet allows one request every 24 hours.
Copy the transaction ID
The faucet confirms with a Successfully sent message and a transaction ID. Copy the ID, since send.mjs needs it to find the source transaction.
Build and broadcast the transaction
With the address funded, build send.mjs part by part in the same folder, so that it spends the faucet output:
Load the key and the source transaction
Create send.mjs. It reads the key from .env, takes the transaction ID of the faucet payment as an argument and fetches that transaction from WhatsOnChain:
import { PrivateKey, P2PKH, Transaction, SatoshisPerKilobyte, Teranode } from '@bsv/sdk'
process.loadEnvFile('.env')
const wif = process.env.TESTNET_WIF
if (wif === undefined) {
throw new Error('TESTNET_WIF is missing from .env, run create-key.mjs first')
}
const key = PrivateKey.fromWif(wif)
const address = key.toAddress('testnet')
const fundingTxid = process.argv[2]
if (fundingTxid === undefined) {
throw new Error('Pass the transaction ID of the faucet payment: node send.mjs FUNDING_TXID')
}
const response = await fetch(`https://api.whatsonchain.com/v1/bsv/test/tx/${fundingTxid}/hex`)
if (!response.ok) {
throw new Error(`WhatsOnChain answered ${response.status} for ${fundingTxid}`)
}
const sourceTransaction = Transaction.fromHex((await response.text()).trim())
const ownLockingScript = new P2PKH().lock(address).toHex()
const sourceOutputIndex = sourceTransaction.outputs.findIndex(
(output) => output.lockingScript.toHex() === ownLockingScript
)
if (sourceOutputIndex === -1) {
throw new Error(`No output of ${fundingTxid} pays ${address}`)
}- The faucet payment can have more than one output, so the script looks for the one whose locking scriptThe part of a transaction output that sets the condition to spend it pays your address, and stops if there is none. It never spends an output that is not yours.
Add the input and the outputs
Add the transaction itself to send.mjs, with one input that spends the faucet output and two outputs:
const tx = new Transaction()
tx.addInput({
sourceTransaction,
sourceOutputIndex,
unlockingScriptTemplate: new P2PKH().unlock(key)
})
tx.addOutput({
lockingScript: new P2PKH().lock(address),
satoshis: 1000
})
tx.addOutput({
lockingScript: new P2PKH().lock(address),
change: true
})P2PKHis a script templateA class that builds a locking script and the unlocking script that spends it for P2PKHPay to Public Key Hash, the standard script that locks coins to an address, the standard output that only the key behind an address can spend.lock(address)builds the locking script of an output, andunlock(key)builds the unlocking scriptThe part of an input that meets the condition set by the locking script of the output it spends of the input when the transaction is signed.- The input carries the whole
sourceTransaction, not only its ID. The SDK reads the amount of the spent output from it to compute the fee, and the broadcaster needs it too. - The first output pays 1,000 satoshisThe smallest unit of BSV. 100,000,000 satoshis make 1 BSV. It pays your own address, so the coins stay with your key. To pay someone else, pass their testnet address to
lock()in this output. - The output with
change: truehas no amount yet. It receives what is left after the payment and the fee.
Compute the fee and sign
Append the fee and the signature to the same file:
await tx.fee(new SatoshisPerKilobyte(1))
await tx.sign()
console.log(`Spends output ${sourceOutputIndex} of ${fundingTxid}, fee ${tx.getFee()} satoshis`)new SatoshisPerKilobyte(1)pays 1 satoshi for each 1,000 bytes, the lowest rate that the testnet endpoint of BSV Broadcaster accepted on 6 November 2026. Read the policy of your endpoint, as Broadcast transactions with BSV Broadcaster shows. With no argument,fee()reads the rate of a Mainnet endpoint.fee()sets the amount of the change output. Call it beforesign(), which throws an error while a change output has no amount.
Broadcast the transaction
Finish the file with the broadcast. A broadcast transaction cannot be undone, so check the outputs and the amounts before you run the script:
const result = await tx.broadcast(new Teranode('https://arcade-v2-testnet-us-1.bsvblockchain.tech/tx'))
if (result.status === 'error') {
throw new Error(`Broadcast failed: ${result.code} ${result.description}`)
}
console.log(`Transaction ID: ${result.txid}`)
console.log(`Explorer: https://test.whatsonchain.com/tx/${result.txid}`)- The
Teranodebroadcaster takes the/txaddress of the testnet endpoint of BSV Broadcaster. It sends the transaction as EFExtended Format (BRC-30): the raw transaction plus the satoshis and locking script of every output it spends, which is why each input needs itssourceTransaction. - A failed broadcast returns
status: 'error'with acodeand adescriptioninstead of throwing, so the script checks the status first.
Run the script
Run send.mjs with the transaction ID of the faucet payment. Replace FUNDING_TXID with the ID you copied from the faucet. An output can be spent only once, so run the script once for each faucet payment:
node send.mjs FUNDING_TXIDSpends output 0 of ce17bfd6...54ff13a0, fee 1 satoshis
Transaction ID: 069a83d1...1c34ef82
Explorer: https://test.whatsonchain.com/tx/069a83d1...1c34ef82The explorer can take a minute or two to list a new transaction. If it says not found and that the transaction may be too new to have arrived, wait and reload.
Your transaction is on testnet, with 1,000 satoshis and the change paid back to your address.
Read the output
The three lines that send.mjs prints describe the transaction you sent:
- The first line gives the index of the faucet output that the input spent, and the fee in satoshis, rounded up from the size of the transaction.
Transaction IDis the ID of the signed transaction, which the SDK computes on your machine. It is printed after BSV Broadcaster answers with success, which means it accepted the transaction for delivery, not that a miner has included it in a block.- The explorer link opens the transaction on the WhatsOnChain testnet explorer, with one input and two outputs: 1,000 satoshis and the change, both to your address.
To follow the transaction until it is mined, ask BSV Broadcaster for its status, as Follow the transaction shows.
Use it in your app
The script keeps every value in one place, so you can move it into your own code. Plan first for the work that a wallet would otherwise do:
- Keep the signed
txobject. Its outputs are new UTXOsUnspent transaction output, and the next transaction can passtxas itssourceTransactionwithout fetching it again. - Record which outputs you have spent. Each output can be spent once, so two transactions that spend the same output cannot both confirm.
- Read the fee rate from the policy of the endpoint you broadcast to, instead of a fixed
1.
The address, the fee rate and the broadcaster endpoint are the testnet values of this script. To go live, move your app to Mainnet and take the Mainnet values from Network endpoints.
Next steps
With a transaction built and broadcast by hand, derive more keys for your outputs: