For the complete documentation index, see llms.txt. This page is also available as Markdown.

Transaction Building

Complete examples for building various types of BSV transactions using the SDK.

Overview

This code feature demonstrates practical transaction building patterns, from simple single-input/output transactions to complex multi-party transactions with custom scripts.

Related SDK Components:

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

See Also

SDK Components:

Learning Paths:

Last updated