How to use the bitcoinjs-lib.TransactionBuilder function in bitcoinjs-lib

To help you get started, we’ve selected a few bitcoinjs-lib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bitcoin-studio / Bitcoin-Programming-with-BitcoinJS / code / data_anchoring_op_return.js View on Github external
const bitcoin = require('bitcoinjs-lib')
const { alice } = require('./wallets.json')
const network = bitcoin.networks.regtest

// Signer
const keyPairAlice1 = bitcoin.ECPair.fromWIF(alice[1].wif, network)
const p2wpkhAlice1 = bitcoin.payments.p2wpkh({pubkey: keyPairAlice1.publicKey, network})

// Build
const txb = new bitcoin.TransactionBuilder(network)

// txb.addInput(prevTx, vout, sequence, prevTxScript)
txb.addInput('TX_ID', TX_VOUT, null, p2wpkhAlice1.output)

const data = Buffer.from('Programmable money FTW!', 'utf8')
const embed = bitcoin.payments.embed({data: [data]})
txb.addOutput(embed.output, 0)
txb.addOutput(p2wpkhAlice1.address, 99900000)

// txb.sign(index, keyPair, redeemScript, sign.hashType, value, witnessScript)
txb.sign(0, keyPairAlice1, null, null, 1e8, null)

const tx = txb.build()
console.log('Transaction hexadecimal:')
console.log(tx.toHex())
github bitcoin-studio / Bitcoin-Programming-with-BitcoinJS / code / swap_on2off_p2wsh_redeem.js View on Github external
const keyPairUser = bitcoin.ECPair.fromWIF(alice[1].wif, network)
const keyPairSwapProvider = bitcoin.ECPair.fromWIF(bob[1].wif, network)

// Generate bitcoin addresses
const p2wpkhSwapProvider = bitcoin.payments.p2wpkh({pubkey: keyPairSwapProvider.publicKey, network})
console.log('Swap provider redeem address:')
console.log(p2wpkhSwapProvider.address)
console.log()

const p2wpkhUser = bitcoin.payments.p2wpkh({pubkey: keyPairUser.publicKey, network})
console.log('User redeem address:')
console.log(p2wpkhUser.address)
console.log()

// Create an instance of BitcoinJS TransactionBuilder
const txb = new bitcoin.TransactionBuilder(network)

// Set timelock
const timelock = bip65.encode({ blocks: TIMELOCK })
if (IS_REFUND) {
  txb.setLockTime(timelock)
  console.log('Timelock expressed in block height:')
  console.log(timelock)
  console.log()
}

// Add input
txb.addInput(TX_ID, TX_VOUT, 0xfffffffe)

// Add outputs
if (IS_REFUND) {
  // Refund case: the user redeems the funds to his address
github bitcoin-studio / Bitcoin-Programming-with-BitcoinJS / code / p2pkh_batching_1_5.js View on Github external
const keyPairAlice1 = bitcoin.ECPair.fromWIF(alice[1].wif, network)

// Recipients
const keyPairBob1 = bitcoin.ECPair.fromWIF(bob[1].wif, network)
const p2pkhBob1 = bitcoin.payments.p2pkh({pubkey: keyPairBob1.publicKey, network})
const keyPairCarol1 = bitcoin.ECPair.fromWIF(carol[1].wif, network)
const p2pkhCarol1 = bitcoin.payments.p2pkh({pubkey: keyPairCarol1.publicKey, network})
const keyPairDave1 = bitcoin.ECPair.fromWIF(dave[1].wif, network)
const p2pkhDave1 = bitcoin.payments.p2pkh({pubkey: keyPairDave1.publicKey, network})
const keyPairEve1 = bitcoin.ECPair.fromWIF(eve[1].wif, network)
const p2pkhEve1 = bitcoin.payments.p2pkh({pubkey: keyPairEve1.publicKey, network})
const keyPairMallory1 = bitcoin.ECPair.fromWIF(mallory[1].wif, network)
const p2pkhMallory1 = bitcoin.payments.p2pkh({pubkey: keyPairMallory1.publicKey, network})

// Create 1 input
const txb = new bitcoin.TransactionBuilder(network)
txb.addInput('TX_ID', TX_VOUT)

// Create 5 outputs
txb.addOutput(p2pkhBob1.address, 2e7)
txb.addOutput(p2pkhCarol1.address, 2e7)
txb.addOutput(p2pkhDave1.address, 2e7)
txb.addOutput(p2pkhEve1.address, 2e7)
txb.addOutput(p2pkhMallory1.address, 2e7)

// Sign
txb.sign(0, keyPairAlice1)

// Build the transaction
const tx = txb.build()
console.log('Transaction hexadecimal:')
console.log(tx.toHex())
github liquality / chainabstractionlayer / packages / bitcoin-swap-provider / lib / BitcoinSwapProvider.js View on Github external
swapVout = vout
      }
    }

    // TODO: Implement proper fee calculation that counts bytes in inputs and outputs
    // TODO: use node's feePerByte
    const txfee = calculateFee(1, 1, 3)

    swapVout.txid = initiationTxHash
    swapVout.vSat = swapVout.value * 1e8

    if (swapVout.vSat - txfee < 0) {
      throw new Error('Transaction amount does not cover fee.')
    }

    const txb = new bitcoin.TransactionBuilder(network)

    if (!isRedeem) txb.setLockTime(expiration)

    const prevOutScript = paymentVariant.output

    txb.addInput(swapVout.txid, swapVout.n, 0, prevOutScript)
    txb.addOutput(addressToString(address), swapVout.vSat - txfee)

    const tx = txb.buildIncomplete()

    const isSegwit = paymentVariantName === 'p2wsh' || paymentVariantName === 'p2shSegwit'

    const sig = await this.getMethod('signP2SHTransaction')(
      initiationTxRaw, // TODO: Why raw? can't it be a bitcoinjs-lib TX like the next one?
      tx,
      address,
github liquality / chainabstractionlayer / packages / bitcoin-bitcoinjs-lib-swap-provider / lib / BitcoinBitcoinJsLibSwapProvider.js View on Github external
const paymentVariantEntry = Object.entries(swapPaymentVariants).find(([, payment]) => payment.output.toString('hex') === vout.scriptPubKey.hex)
      if (paymentVariantEntry) {
        paymentVariantName = paymentVariantEntry[0]
        paymentVariant = paymentVariantEntry[1]
        swapVout = vout
      }
    }

    // TODO: Implement proper fee calculation that counts bytes in inputs and outputs
    // TODO: use node's feePerByte
    const txfee = calculateFee(1, 1, 3)

    swapVout.txid = initiationTxHash
    swapVout.vSat = swapVout.value * 1e8

    const txb = new bitcoin.TransactionBuilder(network)
    txb.setVersion(1)

    if (!isRedeem) txb.setLockTime(expiration)

    const prevOutScript = paymentVariant.output

    txb.addInput(swapVout.txid, swapVout.n, 0, prevOutScript)
    txb.addOutput(addressToString(address), swapVout.vSat - txfee)

    const tx = txb.buildIncomplete()

    const needsWitness = paymentVariantName === 'p2wsh' || paymentVariantName === 'p2shSegwit'

    let sigHash
    if (needsWitness) {
      sigHash = tx.hashForWitnessV0(0, swapPaymentVariants.p2wsh.redeem.output, swapVout.vSat, bitcoin.Transaction.SIGHASH_ALL) // AMOUNT NEEDS TO BE PREVOUT AMOUNT
github liquality / chainabstractionlayer / packages / litecoin-js-wallet-provider / lib / LitecoinJsWalletProvider.js View on Github external
async _buildTransaction (outputs) {
    const network = this._network

    const unusedAddress = await this.getUnusedAddress(true)
    const { inputs, change } = await this.getInputsForAmount(outputs)

    if (change) {
      outputs.push({
        to: unusedAddress,
        value: change.value
      })
    }

    const txb = new bitcoin.TransactionBuilder(network)

    for (const output of outputs) {
      const to = output.to.address === undefined ? output.to : addressToString(output.to) // Allow for OP_RETURN
      txb.addOutput(to, output.value)
    }

    const prevOutScriptType = this.getScriptType()

    for (let i = 0; i < inputs.length; i++) {
      const wallet = await this.getWalletAddress(inputs[i].address)
      const keyPair = await this.keyPair(wallet.derivationPath)
      const paymentVariant = this.getPaymentVariantFromPublicKey(keyPair.publicKey)

      txb.addInput(inputs[i].txid, inputs[i].vout, 0, paymentVariant.output)
    }
github blockstack / blockstack.js / tests / unitTests / src / unitTestsOperations.js View on Github external
'88a51323a9fb8aa4b1e5e4a000000006b483045022100d0c9b1594137186a1dc6c0b3a6' +
        'cbe08399b57e2b8c953584f2ce20bef5642eb902206b9c88b8d2d311db26601acf3068d' +
        'd118649ead4a1f93d029a52c0c61cb2cd2901210236b07942707a86ab666bb300b58d29' +
        '5d988ce9c3a338a0e08380dd98732fd4faffffffff030000000000000000296a2769643' +
        'f363da95bc8d5203d1c07bd87c564a1e6395826cfdfe87cfd31ffa2a3b8101e3e93096f' +
        '2b7c150000000000001976a91441577ec99314a293acbc17d8152137cf4862f7f188ace' +
        '8030000000000001976a9142ebe7b4729185f68c7185c3c6af60fad1b6eeebf88ac00000000'
    const tx = btc.Transaction.fromHex(txHex)
    tx.ins.forEach(x => {
      x.script = null
    })

    const actualLength = txHex.length / 2
    const estimatedLength = estimateTXBytes(tx, 0, 0)

    const tx2 = new btc.TransactionBuilder()
    tx2.addOutput(tx.outs[0].script, 0)
    const estimatedLength2 = estimateTXBytes(tx2, 2, 2)

    t.ok(estimatedLength >= actualLength - 5 && estimatedLength <= actualLength + 5,
         `TX size estimate is roughly accurate? (estimated: ${estimatedLength},
           actual: ${actualLength})`)
    t.ok(estimatedLength2 >= actualLength - 5 && estimatedLength2 <= actualLength + 5,
         `TX size estimate is roughly accurate? (estimated: ${estimatedLength2},
           actual: ${actualLength})`)
  })
github hexonaut / bitcoin-transaction / index.js View on Github external
]).then(function (res) {
		var feePerByte = res[0];
		var utxos = res[1];

		//Setup inputs from utxos
		var tx = new bitcoin.TransactionBuilder(bitcoinNetwork);
		var ninputs = 0;
		var availableSat = 0;
		for (var i = 0; i < utxos.length; i++) {
			var utxo = utxos[i];
			if (utxo.confirmations >= options.minConfirmations) {
				tx.addInput(utxo.txid, utxo.vout);
				availableSat += utxo.satoshis;
				ninputs++;

				if (availableSat >= amtSatoshi) break;
			}
		}

		if (availableSat < amtSatoshi) throw "You do not have enough in your wallet to send that much.";

		var change = availableSat - amtSatoshi;
github liquality / chainabstractionlayer / packages / bitcoin-js-wallet-provider / lib / BitcoinJsWalletProvider.js View on Github external
const totalValue = outputs.reduce((prev, curr) => {
      return prev.plus(BigNumber(curr.value))
    }, BigNumber(0)).toNumber()

    const unusedAddress = await this.getUnusedAddress(true)
    const { inputs, change } = await this.getInputsForAmount(totalValue)

    if (change) {
      outputs.push({
        to: unusedAddress,
        value: change.value
      })
    }

    const txb = new bitcoin.TransactionBuilder(network)

    for (const output of outputs) {
      txb.addOutput(addressToString(output.to), output.value)
    }

    const prevOutScriptType = this.getScriptType()

    for (let i = 0; i < inputs.length; i++) {
      const wallet = await this.getWalletAddress(inputs[i].address)
      const keyPair = await this.keyPair(wallet.derivationPath)
      const paymentVariant = this.getPaymentVariantFromPublicKey(keyPair.publicKey)

      txb.addInput(inputs[i].txid, inputs[i].vout, 0, paymentVariant.output)
    }

    for (let i = 0; i < inputs.length; i++) {
github GridPlus / gridplus-sdk / support / scripts / sendBTC.js View on Github external
.then((utxos) => {
  utxos = utxos.sort((a,b) => {return (a.height > b.height) ? 1 : ((b.height > a.height) ? -1 : 0);} );
  const utxo = utxos[0];
  const txb = new bitcoin.TransactionBuilder(regtest);
  txb.addInput(utxo.hash, utxo.index);
  txb.addOutput(recipient, 1e7);
  txb.addOutput(sender, utxo.value - 1e7 - 1e3);
  txb.sign(0, signer);
  const tx = txb.build().toHex();
  return client.broadcast(tx)
})
.then(() => {