Skip to content

Instantly share code, notes, and snippets.

@bludnic
Created October 23, 2023 12:04
Show Gist options
  • Save bludnic/9cf03ef1d324feac7c7b2a9798bb565e to your computer and use it in GitHub Desktop.
Save bludnic/9cf03ef1d324feac7c7b2a9798bb565e to your computer and use it in GitHub Desktop.
{
async createTransaction(address = '', amount = 0, fee) {
const unspents = await this.getUnspents()
// populate with txHex <--
for (const unspent of unspents) {
const txHex = await this._get(`/tx/${unspent.txid}/hex`)
unspent.txHex = txHex
}
const hex = this._buildTransaction(address, amount, unspents, fee)
let txid = bitcoin.crypto.sha256(Buffer.from(hex, 'hex'))
txid = bitcoin.crypto.sha256(Buffer.from(txid))
txid = txid.toString('hex').match(/.{2}/g).reverse().join('')
return { hex, txid }
},
_buildTransaction(address, amount, unspents, fee) {
amount = new BigNumber(amount).times(this.multiplier).toNumber()
amount = Math.floor(amount)
const txb = new bitcoin.Psbt({
network: this._network
})
txb.setVersion(1)
const target = amount + new BigNumber(fee).times(this.multiplier).toNumber()
let transferAmount = 0
let inputs = 0
unspents.forEach((tx) => {
const amt = Math.floor(tx.amount)
if (transferAmount < target) {
txb.addInput({
hash: tx.txid,
index: tx.vout,
nonWitnessUtxo: Buffer.from(tx.txHex, 'hex')
})
transferAmount += amt
inputs++
}
})
txb.addOutput({
address,
value: amount
})
// This is a necessary step
// If we'll not add a change to output, it will burn in hell
const change = transferAmount - target
if (isPositiveNumber(change)) {
txb.addOutput({
address: this._address,
value: change
})
}
for (let i = 0; i < inputs; ++i) {
txb.signInput(i, this._keyPair)
}
txb.finalizeAllInputs()
const tx = txb.extractTransaction()
return tx.toHex()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment