Skip to content

Instantly share code, notes, and snippets.

@gcharang
Last active April 29, 2023 19:57
Show Gist options
  • Select an option

  • Save gcharang/a2e4874784601a93b226e447d1779f1d to your computer and use it in GitHub Desktop.

Select an option

Save gcharang/a2e4874784601a93b226e447d1779f1d to your computer and use it in GitHub Desktop.
const bitcoin = require("bitgo-utxo-lib");
const axios = require('axios');
// Set your Insight Explorer URL and wif key
const INSIGHT_URL = 'https://doc.dragonhound.info';
const wifKey = "";
/* missing declaration of KMD in bitgo-utxo-lib */
bitcoin.networks.kmd = {
messagePrefix: "\u0018Komodo Signed Message:\n",
bech32: "bc",
bip32: { public: 76067358, private: 76066276 },
pubKeyHash: 60,
scriptHash: 85,
wif: 188,
consensusBranchId: { 1: 0, 2: 0, 3: 1537743641, 4: 1991772603 },
coin: "zec",
};
let keyPair = bitcoin.ECPair.fromWIF(
wifKey,
bitcoin.networks.kmd
);
let KMD_ADDRESS = keyPair.getAddress();
const processUtxos = async utxos => {
let inputs = [];
for (const utxo of utxos) {
inputs.push({
txId: utxo.txid,
vout: utxo.vout,
satoshis: utxo.satoshis
});
}
let txb = new bitcoin.TransactionBuilder(bitcoin.networks.kmd);
txb.setVersion(bitcoin.Transaction.ZCASH_SAPLING_VERSION);
txb.setVersionGroupId(0x892f2085);
txb.setLockTime(Math.floor(Date.now() / 1000) - 7777); //locktime set slightly in the past
txb.setExpiryHeight(0);
inputs.forEach((input) => txb.addInput(
input.txId,
input.vout,
0xffffffff - 1
));
const totalValue = utxos.reduce((sum, utxo) => sum + utxo.satoshis, 0);
txb.addOutput(KMD_ADDRESS, totalValue - 2e4); //sending back `all - txnFee`
inputs.forEach((input, index) => {
txb.sign(index, keyPair, "", bitcoin.Transaction.SIGHASH_ALL, input.satoshis);
});
let tx = txb.build();
const hex = tx.toHex()
console.log("txid: " + tx.getId());
console.log("hex: " + hex);
try {
let postResponse = axios.post(`${INSIGHT_URL}/insight-api-komodo/tx/send`, JSON.stringify({ rawtx: hex }), {
headers: {
'Content-Type': 'application/json'
}
})
} catch (error) {
console.log(error)
}
await delay(3000)
}
const delay = ms => new Promise(res => setTimeout(res, ms));
async function consolidateUtxos() {
try {
const utxosResponse = await axios.get(`${INSIGHT_URL}/insight-api-komodo/addr/${KMD_ADDRESS}/utxo`);
let utxos = utxosResponse.data;
utxos = utxos.filter(utxo => utxo.satoshis !== 10000)
if (utxos.length === 0) {
console.log(`No UTXOs found for address ${KMD_ADDRESS}`);
return;
}
let steps = Math.ceil(utxos.length / 50)
for (let index = 0; index < steps; index++) {
await processUtxos(utxos.slice(index * 50, (index + 1) * 50))
}
} catch (error) {
console.error('Error consolidating UTXOs:', error.message);
}
}
consolidateUtxos();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment