Skip to content

Instantly share code, notes, and snippets.

@ac12644
Created August 15, 2023 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ac12644/7d0bc0befb598c771aa982174834c913 to your computer and use it in GitHub Desktop.
Save ac12644/7d0bc0befb598c771aa982174834c913 to your computer and use it in GitHub Desktop.
const bitcore = require("bitcore-lib");
const axios = require("axios");
exports.childPaysForParent = async (req, res) => {
try {
// Load the Bitcoin private key
const privateKey = new bitcore.PrivateKey.fromWIF(process.env.BITCOIN_PRIVATE_KEY, testnet);
const address = privateKey.toAddress(testnet);
// Fetch the unspent transaction outputs (UTXOs)
const { data: utxos } = await axios.get(`https://blockstream.info/testnet/api/address/${address}/utxo`);
// Identify the unconfirmed UTXO (the parent transaction we want to expedite)
const unconfirmedUtxo = utxos.find(utxo => utxo.status.confirmed === false);
if (!unconfirmedUtxo) {
return res.status(400).send({ error: "No unconfirmed UTXOs found." });
}
const transaction = new bitcore.Transaction();
const scriptPubKey = bitcore.Script.buildPublicKeyHashOut(privateKey.toPublicKey()).toString();
// Use the unconfirmed UTXO in our new transaction
transaction.from({
txId: unconfirmedUtxo.txid,
outputIndex: unconfirmedUtxo.vout,
script: scriptPubKey,
satoshis: unconfirmedUtxo.value
});
const fee = 100000; // Higher fee than the parent transaction
const remaining = unconfirmedUtxo.value - fee;
transaction.change(address);
transaction.fee(fee);
transaction.sign(privateKey);
const serializedTransaction = transaction.serialize();
const { data: result } = await axios.post(
"https://api.blockcypher.com/v1/btc/test3/txs/push",
{ tx: serializedTransaction }
);
res.send({ txId: result.tx.hash });
} catch (error) {
console.error(error);
res.status(500).send({ error: error.message });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment