Transaction Building
Overview
Simple Transaction Builder
import { Transaction, PrivateKey, P2PKH, Script } from '@bsv/sdk'
/**
* Simple Transaction Builder
*
* Builds a basic transaction with one input and two outputs (payment + change)
*/
class SimpleTransactionBuilder {
/**
* Create a simple payment transaction
*/
async buildPayment(
fromPrivateKey: PrivateKey,
toAddress: string,
amount: number,
utxo: UTXO
): Promise<Transaction> {
const tx = new Transaction()
// Add input from UTXO
tx.addInput({
sourceTXID: utxo.txid,
sourceOutputIndex: utxo.vout,
unlockingScriptTemplate: new P2PKH().unlock(fromPrivateKey),
sequence: 0xffffffff
})
// Add payment output
tx.addOutput({
satoshis: amount,
lockingScript: Script.fromAddress(toAddress)
})
// Add change output
const fee = 500
const changeAmount = utxo.satoshis - amount - fee
if (changeAmount > 0) {
tx.addOutput({
satoshis: changeAmount,
lockingScript: new P2PKH().lock(fromPrivateKey.toPublicKey().toHash())
})
}
// Sign transaction
await tx.sign()
return tx
}
}
/**
* Usage Example
*/
async function example() {
const builder = new SimpleTransactionBuilder()
const privateKey = PrivateKey.fromWif('your-wif-key')
const utxo: UTXO = {
txid: 'abc123...',
vout: 0,
satoshis: 100000,
script: new P2PKH().lock(privateKey.toPublicKey().toHash())
}
const tx = await builder.buildPayment(
privateKey,
'1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
50000,
utxo
)
console.log('Transaction ID:', tx.id('hex'))
}Multi-Input Transaction Builder
Advanced Transaction Builder
Batch Payment Builder
Related Examples
See Also
Last updated
