I’ve created a testnet transaction utilizing blockcypher API and BitcoinJs-lib , I guarantee solely unpsent stability are added to my trasaction enter
But it surely’s returning error:
Error validating transaction: Transaction abdb49e4....f72497 referenced by enter 0 of ef480....0ffc0e5 has already been spent..'
here’s a pattern code I am working
const btcnetwork = BitcoinJsLib.networks.testnet
const bip32 = BIP32Factory(tinySec)
const rootSeed = await bip39.mnemonicToSeed(mnemonic)
const root = bip32.fromSeed(rootSeed, btcnetwork)
const accountNode = root.derivePath("m/84'/1'/0'")
const addressNode = accountNode.derive(0).derive(0)
const p2wpkh = funds.p2wpkh({
pubkey: addressNode.publicKey,
community: btcnetwork,
})
const p2sh = funds.p2sh({
redeem: p2wpkh,
community: btcnetwork
})
const psbt = new BitcoinJsLib.Psbt({ community: btcnetwork })
const unspentTxOuts = await fetch(`https://api.blockcypher.com/v1/btc/test3/addrs/${p2wpkh.deal with}/full`).then(response => response.json());
let inputIndex = -1
let totalValue = 0
for (let i = 0; i < unspentTxOuts.txs.size; i++) {
const tx = unspentTxOuts.txs[i]
for (let j = 0; j < tx.outputs.size; j++) {
const output = tx.outputs[j]
if (output.addresses[0] === p2wpkh.deal with && !output.spent_by) {
totalValue += output.worth
inputIndex = tx.inputs[0].output_index,
psbt.addInput({
hash: tx.hash,
index: tx.inputs[0].output_index,
witnessUtxo: {
script: Buffer.from(output.script, 'hex'),
worth: output.worth
},
redeemScript: p2sh.redeem?.output
})
break
}
}
}
if (inputIndex === -1 && totalValue < (Math.ground(quantity * 1e8) - 1000)) {
console.log(`No unspent transaction outputs discovered for deal with ${p2sh.deal with}`)
return
}
psbt.addOutput({
deal with: recipientAddress,
worth: Math.ground(quantity * 1e8),
})
const changeValue = unspentTxOuts.final_balance - Math.ground(quantity * 1e8) - 1000; // Calculate change worth with a charge of 1000 satoshi
if (changeValue > 0) {
psbt.addOutput({
deal with: p2wpkh.deal with,
worth: changeValue,
});
}
for (let i = 0; i < psbt.inputCount; i++) {
psbt.signInput(i, addressNode)
}
psbt.finalizeAllInputs()
const txHex = psbt.extractTransaction().toHex()
const consequence = await fetch('https://api.blockcypher.com/v1/btc/test3/txs/push', {
technique: 'POST',
physique: JSON.stringify({ tx: txHex }),
headers: { 'Content material-Sort': 'software/json' },
})
const res = await consequence.json()
console.log(`Despatched ${quantity} BTC to ${recipientAddress} from ${p2wpkh.deal with}, TX Hash: ${res?.txid}`)
I do know I solely had enter which can be unspent and the blockcypher api’s are good, is there one thing I am lacking please?
