Prepairing/Building a btc transaction in JS with "
bitcoinjs-lib" takes a few more steps than generating a new public address/private key.
This include following steps: Create a new transaction, add in- and outputs, sign the transaction and build it to get the raw transaction hex to be able to broadcast the transaction.
First obvious step is to install the library.
Now import the library and setup the network configuration for the transaction:
const bitcoin = require('bitcoinjs-lib');
const network = bitcoin.networks.bitcoin;
If you want to use the testnet replace it with "
bitcoin.networks.testnet"
Next step is to setup the variables of the sender adresses. You will need the private key in WIF-format to be able to sign the transaction later:
const privateKeyWIF = 'insert_privkey_here';
const keyPair = bitcoin.ECPair.fromWIF(privateKeyWIF, network);
Add the transaction ID and the output index of the UTXO you want to spend:
const txId = 'insert_txId_here';
const vout = 0;
Define the receiving address, the amount and the fee that you are using for the transaction:
const recipientAddress = 'insert_address_here';
const amountToSend = insert_amount_in_satoshi_here;
const fee = insert_fee_amount_in_satoshi_here;
We can finally build ur transaction by adding the input and output:
const txBuilder = new bitcoin.TransactionBuilder(network);
txBuilder.addInput(txId, vout);
txBuilder.addOutput(recipientAddress, amountToSend);
Now sign the transaction with the private key that we set up in the first step:
txBuilder.sign(0, keyPair);
Lets finish and compile it to get raw transaction hex:
const rawTx = txBuilder.build().toHex();
console.log("Raw Transaction Hex: ", rawTx);
With the output you are finally able to broadcast your transaction to the network. There are a few services that offer to push ur transaction by using the raw transaction hex.
One example would be
Blockstream - just enter the raw transaction hex and the transaction will be broadcasted.