Created
October 23, 2023 12:04
-
-
Save bludnic/9cf03ef1d324feac7c7b2a9798bb565e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
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