Skip to content

Commit

Permalink
broast succ/return fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
Harshit Singhal authored and Harshit Singhal committed Feb 13, 2025
1 parent 2c66f17 commit fd86f03
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 63 deletions.
136 changes: 76 additions & 60 deletions src/send_tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,17 @@ async function test_send() {
const { address: senderAddress, output: senderScript } = bitcoin.payments.p2wpkh({ pubkey: Buffer.from(keyPair.publicKey), network: NETWORK, });
console.log("Address: ", senderAddress);
console.log("senderScript: ", senderScript);
// console.log(NETWORK);
// console.log(keyPair);
userInfo = await fetch_user_info(senderAddress);
tx_Ref = userInfo.txrefs[0];

const utxo = {
txId: tx_Ref.tx_hash,
vout: tx_Ref.tx_output_n, // Output index in the previous TX
value: tx_Ref.value // Amount in satoshis (0.001 BTC)
}

const utxo = await fetchUTXO(senderAddress);
console.log(utxo)

const receiverAddress = 'tb1qa5y6kx2rmy7jhhddp5cp92mvkxl0mj5lwegner';
fee = 10;
const sendAmount = 620;
fee = 150;
const sendAmount = 820;

// console.log(NETWORK.bech32);
// console.log(fromBech32(receiverAddress))

psbt = createTransaction(senderScript, utxo, receiverAddress, sendAmount);
psbt = createTransaction(senderScript, utxo, fee, receiverAddress, sendAmount);

console.log(psbt);
psbt.signInput(0, {
publicKey: Buffer.from(keyPair.publicKey),
sign: (hash) => {
Expand All @@ -47,57 +37,18 @@ async function test_send() {
});
psbt.finalizeAllInputs();

console.log(psbt);


const rawTxHex = psbt.extractTransaction().toHex();
console.log('Raw Transaction Hex:', rawTxHex);

//broadcasting now
// //broadcasting now
broadcastTransaction(rawTxHex);


};

async function broadcastTransaction(rawTxHex) {
try {
const response = await axios.post('https://blockstream.info/testnet/api/tx', rawTxHex, {
headers: { 'Content-Type': 'text/plain' }
});
console.log('Transaction broadcasted successfully!', response.data);
} catch (error) {
console.error('Error broadcasting transaction:', error.response ? error.response.data : error.message);
}
}

function fromBech32(address) {
let result;
let version;
try {
result = bech32_1.bech32.decode(address);
} catch (e) {}
if (result) {
version = result.words[0];
if (version !== 0) throw new TypeError(address + ' uses wrong encoding');
} else {
result = bech32_1.bech32m.decode(address);
version = result.words[0];
if (version === 0) throw new TypeError(address + ' uses wrong encoding');
}
const data = bech32_1.bech32.fromWords(result.words.slice(1));
return {
version,
prefix: result.prefix,
data: Buffer.from(data),
};
}

function getScriptPubKey(address, network) {
const { data } = bitcoin.address.fromBech32(address); // Decode Bech32
const scriptPubKey = bitcoin.script.compile([bitcoin.opcodes.OP_0, data]); // OP_0 <HASH>

console.log('🚀 scriptPubKey (Hex):', scriptPubKey.toString('hex'));
return scriptPubKey;
}

function createTransaction(senderScript, utxo, recipientAddress, sendAmount) {
function createTransaction(senderScript, utxo, fee, recipientAddress, sendAmount) {
psbt = new bitcoin.Psbt({ NETWORK });
psbt.setVersion(2);
psbt.setLocktime(0);
Expand All @@ -115,9 +66,74 @@ function createTransaction(senderScript, utxo, recipientAddress, sendAmount) {
script: getScriptPubKey(recipientAddress, NETWORK),
value: sendAmount,
});

psbt.addOutput({
script: Buffer.from(senderScript, 'hex'),
value: utxo.value - sendAmount - fee,
})
return psbt;
}

async function fetchUTXO(address) {
try {
const response = await axios.get(`https://blockstream.info/testnet/api/address/${address}/utxo`);
if (!response.data.length) throw new Error("No UTXOs found for this address.");

// ✅ Select the first available UTXO
const utxo = response.data[0];

return {
txId: utxo.txid,
vout: utxo.vout,
value: utxo.value
};
} catch (error) {
console.error('❌ Error fetching UTXO:', error.message);
process.exit(1);
}
}

async function broadcastTransaction(rawTxHex) {
try {
const response = await axios.post('https://blockstream.info/testnet/api/tx', rawTxHex, {
headers: { 'Content-Type': 'text/plain' }
});
console.log('Transaction broadcasted successfully!', response.data);
} catch (error) {
console.error('Error broadcasting transaction:', error.response ? error.response.data : error.message);
}
}

// function fromBech32(address) {
// let result;
// let version;
// try {
// result = bech32_1.bech32.decode(address);
// } catch (e) {}
// if (result) {
// version = result.words[0];
// if (version !== 0) throw new TypeError(address + ' uses wrong encoding');
// } else {
// result = bech32_1.bech32m.decode(address);
// version = result.words[0];
// if (version === 0) throw new TypeError(address + ' uses wrong encoding');
// }
// const data = bech32_1.bech32.fromWords(result.words.slice(1));
// return {
// version,
// prefix: result.prefix,
// data: Buffer.from(data),
// };
// }

function getScriptPubKey(address, network) {
const { data } = bitcoin.address.fromBech32(address); // Decode Bech32
const scriptPubKey = bitcoin.script.compile([bitcoin.opcodes.OP_0, data]); // OP_0 <HASH>

console.log('🚀 scriptPubKey (Hex):', scriptPubKey.toString('hex'));
return scriptPubKey;
}

async function fetch_user_info(address) {
try {
const url = `https://api.blockcypher.com/v1/btc/test3/addrs/${address}?unspentOnly=true?includeScript=true`;
Expand Down
42 changes: 39 additions & 3 deletions src/test_wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,31 @@ async function test_user() {
// console.log(userInfo);
// console.log(userInfo.txrefs[0].tx_hash);
// const tx_ref = userInfo.txrefs
txInfo = await fetch_tx_info(userInfo.txrefs[0].tx_hash);
console.log(txInfo);
// txInfo = await fetch_tx_info(userInfo.unconfirmed_txrefs[0]);
// console.log(txInfo);

fetchUTXO(address);

//testnetFee Estimate
// console.log(await fetch_feeEstimate());
};

async function fetch_feeEstimate() {
try {
const url = `https://blockstream.info/testnet/api/fee-estimates`;
const response = await axios.get(url);

if (response.data) {
return response.data; // Balance in satoshis
}
} catch (error) {
console.error("Error fetching information:", error.response ? error.response.data : error.message);
}
}

async function fetch_user_info(address) {
try {
const url = `https://api.blockcypher.com/v1/btc/test3/addrs/${address}?unspentOnly=true?includeScript=true`;
const url = `https://blockstream.info/testnet/api/address/${address}`;
const response = await axios.get(url);

if (response.data) {
Expand All @@ -48,6 +66,24 @@ async function fetch_tx_info(tx_hash) {
console.error("Error fetching information:", error.response ? error.response.data : error.message);
}
}
async function fetchUTXO(address) {
try {
const response = await axios.get(`https://blockstream.info/testnet/api/address/${address}/utxo`);
if (!response.data.length) throw new Error("No UTXOs found for this address.");

// ✅ Select the first available UTXO
const utxo = response.data[0];

return {
txId: utxo.txid,
vout: utxo.vout,
value: utxo.value
};
} catch (error) {
console.error('❌ Error fetching UTXO:', error.message);
process.exit(1);
}
}


test_user();
Expand Down

0 comments on commit fd86f03

Please sign in to comment.