# Build a transaction from inputs and outputs

> For the complete documentation index, see [llms.txt](https://bsvblockchain.com/docs/llms.txt).

Build, sign and broadcast a BSV transaction with @bsv/sdk, with one input spent through a P2PKH script template, a payment output and a change output, on testnet.

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](https://bsvblockchain.com/docs/guides/services/broadcasting/). 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/sdk` requires.
- [BSV Desktop](https://bsvblockchain.com/docs/wallets/bsv-desktop/) on testnet, to sign in to the testnet faucet. If you do not have it yet, follow [Set up a testnet wallet](https://bsvblockchain.com/docs/get-started/quick-start-browser/#set-up-a-testnet-wallet).

## How it works

Two scripts and three services take part:

- `create-key.mjs` creates a testnet private key, writes it to `.env` and prints the address of that key.
- The faucet (A site that sends free test coins to an address) at [bsvfaucet.com](https://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.mjs` fetches the source transaction from the [WhatsOnChain](https://test.whatsonchain.com/) 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](https://bsvblockchain.com/docs/concepts/transactions/) 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:

**1. Install the SDK**

Create an empty folder, open it in the terminal and install [`@bsv/sdk`](https://bsvblockchain.com/docs/sdk/typescript/):

```bash
npm init -y
npm install @bsv/sdk
```

This page was written against `@bsv/sdk` 4.0.1.

**2. Keep the key out of git**

Add a `.gitignore` file to the project folder, so the key never reaches a repository:

```text .gitignore
.env
node_modules/
```

**3. 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:

```javascript create-key.mjs
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 WIF (Wallet Import Format, a text encoding of a private key) with the testnet prefix, and the script stores it in `.env` as `TESTNET_WIF`.
- `toAddress('testnet')` returns the testnet address of the key. With no argument, it returns a Mainnet address.
- The script checks first that `.env` does not exist, so running it again does not replace a key that already holds coins.

**4. Run the script**

Run it once:

```bash
node create-key.mjs
```

```text
Testnet address: mngg4eaf...dvwWyTM
```

The 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:

**1. Request coins from the faucet**

Follow [Get free testnet coins](https://bsvblockchain.com/docs/get-started/quick-start-browser/#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.

**2. 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:

**1. 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:

```javascript send.mjs
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 script (The 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.

**2. Add the input and the outputs**

Add the transaction itself to `send.mjs`, with one input that spends the faucet output and two outputs:

```javascript send.mjs
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
})
```

- `P2PKH` is a script template (A class that builds a locking script and the unlocking script that spends it) for P2PKH (Pay 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, and `unlock(key)` builds the unlocking script (The 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 satoshis (The 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: true` has no amount yet. It receives what is left after the payment and the fee.

**3. Compute the fee and sign**

Append the fee and the signature to the same file:

```javascript send.mjs
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](https://bsvblockchain.com/docs/guides/services/broadcasting/) shows. With no argument, `fee()` reads the rate of a Mainnet endpoint.
- `fee()` sets the amount of the change output. Call it before `sign()`, which throws an error while a change output has no amount.

**4. 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:

```javascript send.mjs
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 `Teranode` broadcaster takes the `/tx` address of the testnet endpoint of BSV Broadcaster. It sends the transaction as EF (Extended Format (BRC-30): the raw transaction plus the satoshis and locking script of every output it spends), which is why each input needs its `sourceTransaction`.
- A failed broadcast returns `status: 'error'` with a `code` and a `description` instead of throwing, so the script checks the status first.

**5. 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:

```bash
node send.mjs FUNDING_TXID
```

```text
Spends output 0 of ce17bfd6...54ff13a0, fee 1 satoshis
Transaction ID: 069a83d1...1c34ef82
Explorer: https://test.whatsonchain.com/tx/069a83d1...1c34ef82
```

> The 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 ID` is 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](https://bsvblockchain.com/docs/guides/services/broadcasting/#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 `tx` object. Its outputs are new UTXOs (Unspent transaction output), and the next transaction can pass `tx` as its `sourceTransaction` without 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](https://bsvblockchain.com/docs/guides/go-to-mainnet/) and take the Mainnet values from [Network endpoints](https://bsvblockchain.com/docs/reference/networks/).

## Next steps

With a transaction built and broadcast by hand, derive more keys for your outputs:

- [Derive HD keys with BIP32](https://bsvblockchain.com/docs/sdk/typescript/low-level/hd-keys/)