So I am using this NPM package ( https://www.npmjs.com/package/bitcore-lib )
to create and sign a Bitcoin legacy transaction locally and it was working fine for legacy.
But when I tried to do the same for segwit addresses I started getting this error when i submit that raw into sendrawtransasction node method.
mandatory-script-verify-flag-failed (Witness requires empty scriptSig)
So I think the issue is with this package as the structure of this payment is not what is required for a SegWit transaction.
So my main question is is there any package in javascript I can use to create and sign a transaction? the main payload I have is
receipentAddress, senderAddress, amount ( in satoshis ), and privateKey in WIF.
any help or clue is highly appreciated.
//edit:
rawhex:
02000000017d155e9418b60ee26fe189d4381a1fcd5aac1d8eed5216c210e6f6e7a6d86b37010000006a47304402204d6b08238b2eafbf18b7b940a4bbb59c1cc610a1d5e05d2ed72f78f9a6035b890220513a33b2461f12f711776063a54d62913adef76eb40f62ad0eac3f16577c572e01210312bc181f50c9dff7d5ebe77d4df32a9ae2e5b0530b5a4a9c4b8b88647911a883ffffffff029065000000000000160014dc804b4f932f37f77ff9a4f843c845dc3cc3d30164f20300000000001600149518ea8b88e82e82d9003fa3f7518e15180cc58500000000
edit: added code below
const axios = require('axios');
const bitcore = require('bitcore-lib');
async function generateAndSignTransaction(payload) {
let { address, privateKey, recipientAddress, satoshis, chain } = payload;
try {
async function fees() {
try {
let key;
if (chain === "testnet"){
key = 'test3'
}else {
key = 'main'
}
let r = await axios.get(`https://api.blockcypher.com/v1/btc/${key}`);
let feeObj = new Object;
feeObj["High_fee"] = r.data.high_fee_per_kb;
feeObj["Medium_fee"] = r.data.medium_fee_per_kb;
feeObj["Low_fee"] = r.data.low_fee_per_kb;
return feeObj;
} catch (error) {
console.error(error);
throw error; // Propagate error
}
}
let res = await fees();
let fee = res.Low_fee;
let url = `https://blockstream.info/${chain}/api/address/${address}/utxo`;
res = await axios.get(url);
console.log('UTXOS: ', res.data);
let i = 0;
let utxos = [];
let balance_utxos = 0;
while (balance_utxos <= satoshis + fee && i < res.data.length) {
let utxo = {
"txId": res.data[i].txid,
"outputIndex": res.data[i].vout,
"script": bitcore.Script.buildPublicKeyHashOut(address).toString(),
"satoshis": res.data[i].value
};
utxos.push(utxo);
balance_utxos += res.data[i].value;
i++;
}
console.log('UTXOS 02: ', utxos);
let tx = new bitcore.Transaction();
tx.from(utxos);
tx.to(recipientAddress, satoshis);
tx.change(address);
tx.fee(fee);
tx.inputs.forEach(input => {
input.setScript(bitcore.Script.empty());
});
tx.sign(privateKey);
console.log('Tramsactopnm: ', tx);
console.log('Tramsactopnm data: ', tx.serialize());
let txnHex = tx.toString();
return { txid: txnHex }; // Return the serialized transaction
} catch (error) {
console.error('Error:', error);
throw error; // Propagate error
}
}
module.exports = { generateAndSignTransaction };