Transaction Creation
Overview
Prerequisites
Code Example
import { Transaction, P2PKH, PrivateKey, SatoshisPerKilobyte } from '@bsv/sdk'
async function createBasicTransaction() {
// 1. Set up your private key
const privateKey = PrivateKey.fromWif('your-private-key-wif')
const sourceAddress = privateKey.toPublicKey().toAddress()
// 2. Create a new transaction
const tx = new Transaction()
// 3. Add input from a UTXO you own
const utxo = {
txid: 'previous-transaction-id',
vout: 0,
satoshis: 10000,
script: new P2PKH().lock(sourceAddress)
}
await tx.addInput({
sourceTransaction: utxo.txid,
sourceOutputIndex: utxo.vout,
unlockingScriptTemplate: new P2PKH().unlock(privateKey),
sequence: 0xffffffff
})
// 4. Add output (payment to recipient)
const recipientAddress = 'recipient-bsv-address'
const paymentAmount = 5000 // satoshis
tx.addOutput({
satoshis: paymentAmount,
lockingScript: new P2PKH().lock(recipientAddress)
})
// 5. Calculate and add change output
const feeModel = new SatoshisPerKilobyte(50) // 50 sats/KB
const estimatedFee = await tx.getFee(feeModel)
const changeAmount = utxo.satoshis - paymentAmount - estimatedFee
if (changeAmount > 0) {
tx.addOutput({
satoshis: changeAmount,
lockingScript: new P2PKH().lock(sourceAddress)
})
}
// 6. Sign the transaction
await tx.sign()
// 7. Serialize for broadcasting
const rawTx = tx.toHex()
console.log('Transaction hex:', rawTx)
console.log('Transaction ID:', tx.id('hex'))
return tx
}
// Run the example
createBasicTransaction()
.then(tx => console.log('Transaction created successfully'))
.catch(err => console.error('Error creating transaction:', err))Explanation
Step-by-Step Breakdown
Key Concepts
Inputs
Outputs
Fees
Common Variations
Multiple Inputs
Multiple Recipients
Related Components
Related Code Features
Learning Path References
Error Handling
Best Practices
Last updated
