Skip to main content
1 of 2

Bitcoinjs-lib how to add multiple utxos in addInput

Hi i want to make transactions of bitcoin bech32 addresses using bitcoinjs-lib , here is my code below, it works fine when my address has only one utxos but when it increases to two or more as its array which doesn't pass into addInput method, so it fails. Please help me out to loop through it or what is the solution to handle multiple utxo as input. Thanks

const bitcoin = require("bitcoinjs-lib");

//creating and signing a native p2wpkh
//p2wpk: addInput('00000....', 0, prevOutScript)
//sign(0, keyPair,,,value)

let NETWORK = bitcoin.networks.litecoin; 
let txb = new bitcoin.TransactionBuilder(NETWORK);

//get unspent output details
let txid = "9d1517a2499ce5496ba3c826785b25982c63dc5b59b0c256303bf19128e44747"; //transaction id of the output you want to spend
let outn = 0;  // n out

let keypair = bitcoin.ECPair.fromWIF(WIF, NETWORK);
let scriptPubkey = bitcoin.script.witnessPubKeyHash.output.encode(
                       bitcoin.crypto.hash160(  
                           keypair.getPublicKeyBuffer()
                       )
                   );

//add input
txb.addInput(txid, outn, null, scriptPubkey);

//add output
txb.addOutput("ltc1q9umns6nuxv3xrhzdwlmhkzujewu6hulyuwgx30",4999000); //first argument is receiving address, the second is the amount we are sending after deducting a mining fee

//signing
txb.sign(0, keypair, null, null, 5000000); //NOTE the amount is the FULL amount of the unspent output, NOT the amount we are sending
let tx = txb.build();
let txhex = tx.toHex();

console.log(txhex);