Skip to content

Instantly share code, notes, and snippets.

@aniketdivekar
Last active November 15, 2023 14:47
Show Gist options
  • Save aniketdivekar/7af69c124507ff4d3b868614d86b6ebb to your computer and use it in GitHub Desktop.
Save aniketdivekar/7af69c124507ff4d3b868614d86b6ebb to your computer and use it in GitHub Desktop.
const bitcoin = require('bitcoinjs-lib')
const psbt = new bitcoin.Psbt({ network: bitcoin.networks.testnet })
// example transaction
const unspentOutput = {
"txid": "11e5b7005a76c8a53f9a0036bc1a2745ebd73ad40017b3169894aa2c19e789d7",
"vout": 1,
"address": "2NCxBSjMaVeBFyxmGcD2X428v6k5n3pCQKN",
"label": "payment",
"redeemScript": "001495a994a417c45f97c87d03efb21997452d4c782f",
"scriptPubKey": "a914d82952189f437226406ec17c8c397a34af177cd187",
"amount": 1.00000000,
"confirmations": 24,
"spendable": true,
"solvable": true,
"desc": "sh(wpkh([7fc5659a/0'/0'/1']02284916d8cd4fdf35574d5f0aaea0c93607254b06601ef126e73d8fb075b7169f))#6k9sssw6",
"safe": true
}
// get transaction hex and check if it's a Segwit or Non-Segwit transaction
const rawTransaction = getRawHex(unspentOutput.txid) // you can use `gettransaction` rpc to get the transaction hex
if (isSegwit) {
// add segwit transaction input
psbt.addInput({
hash: unspentOutput.txid,
index: unspentOutput.vout,
witnessUtxo: {
script: Buffer.from(unspentOutput.scriptPubKey, 'hex'),
value: unspentOutput.amount * 100000000 // value in satoshi
},
redeemScript: Buffer.from(unspentOutput.redeemScript, 'hex')
})
} else {
// add non-segwit transaction input
psbt.addInput({
hash: unspentOutput.txid,
index: unspentOutput.vout,
nonWitnessUtxo: Buffer.from(rawTransaction, 'hex'),
redeemScript: Buffer.from(unspentOutput.redeemScript, 'hex')
})
}
// add output - destination address and the amount to transfer to
psbt.addOutput({
address: '2NF3WNhdXJzgChaAZgdYjHWaAvYG25Nhz58',
value: 50000000 // value is satoshi (0.5 BTC)
})
// We have input of 1 BTC and we are trying to send 0.5 BTC
// If we just use these configurations to send the transaction, it will consume remaining 0.5 BTC as fees
// which you wouldn't want
// So leave some fee for the transaction, let's say 0.001 BTC and send the remaining amount to change address
// change address is the address you own where change from the transaction can be sent to
psbt.addOutput({
address: '2MzaZzn4cuAByJrNRpDHEgE8Z55Y7dsi3Gq', // change address
value: 49900000 // value is satoshi (0.499 BTC)
})
// create transaction end
@yashwanth2804
Copy link

// check if it's a Segwit or Non-Segwit transaction
const isSegwit = rawTransaction.substring(8, 12) === '0001'

before conditional check of the segwit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment