aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--routes/bitcoin/sweep.js40
1 files changed, 32 insertions, 8 deletions
diff --git a/routes/bitcoin/sweep.js b/routes/bitcoin/sweep.js
index 37efb73f..8b7bf5aa 100644
--- a/routes/bitcoin/sweep.js
+++ b/routes/bitcoin/sweep.js
@@ -9,14 +9,25 @@ const network = prod
: bitcoin.networks["regtest"];
module.exports = async (req, res) => {
- let ecpair = bitcoin.ECPair.fromWIF('cVosbTBiXp7LYSiGVRZfZnrEjpao4X4CUTG7Ze21XM3zFTLPCMvk', network);
+ let ecpair = bitcoin.ECPair.fromWIF(
+ "cVosbTBiXp7LYSiGVRZfZnrEjpao4X4CUTG7Ze21XM3zFTLPCMvk",
+ network
+ );
let { address: from, amount, feeRate, target } = req.body;
let utxos;
- if (!feeRate)
- feeRate = ((await bc.estimateSmartFee(6)).feerate * SATS);
+ if (!feeRate) feeRate = (await bc.estimateSmartFee(6)).feerate * SATS;
feeRate = Math.round(feeRate / 1000);
l.info("sweeping", req.user.username, from, amount, feeRate);
+
+ let {
+ data: {
+ chain_stats: { funded_txo_sum: funded, spent_txo_sum: spent }
+ }
+ } = await axios.get(`${api}/address/${from}`);
+
+ let balance = funded - spent;
+
try {
({ data: utxos } = await axios.get(`${api}/address/${from}/utxo`));
} catch (e) {
@@ -32,28 +43,41 @@ module.exports = async (req, res) => {
let { inputs, outputs, fee } = coinselect(utxos, targets, feeRate);
- if (!inputs || !outputs) return res.status(500).send("Unable to construct sweep transaction, try a lower fee rate?");
+ if (balance === amount) {
+ delete targets[0].value;
+ ({ inputs, outputs, fee } = split(utxos, targets, feeRate));
+ l.info("split", inputs, outputs, fee);
+ }
+
+ if (!inputs || !outputs)
+ return res
+ .status(500)
+ .send("Unable to construct sweep transaction, try a lower fee rate?");
let psbt = new bitcoin.Psbt({ network });
+ let total = 0;
outputs.map(({ address, value }) => {
+ total += value;
psbt = psbt.addOutput({
address: address || from,
value
- })
+ });
});
for (let i = 0; i < inputs.length; i++) {
let { txid, vout } = inputs[i];
- let nonWitnessUtxo = Buffer.from(await bc.getRawTransaction(txid), 'hex');
+ let nonWitnessUtxo = Buffer.from(await bc.getRawTransaction(txid), "hex");
psbt = psbt.addInput({
hash: txid,
index: vout,
- nonWitnessUtxo,
+ nonWitnessUtxo
});
}
feeRate = Math.round(feeRate * 1000);
psbt = psbt.toBase64();
- res.send({ feeRate, psbt });
+
+ console.log(total);
+ res.send({ feeRate, psbt, total });
};