Simple Bitcoin Transaction 1–1 2019–2020 | NodeJs

JavaScript Tutorials by Ivan Cabral

Ivan Cabral
Dec 22, 2019 · 3 min read

I create my first wallet in 2017 and I must confess what this is hard at begin, but learning and with practice this is easy

Different developers search how to make bitcoin transactions but they have insufficient information and leaves that work for this, I will explain to you how to create that transaction and provide you my own module for making these transactions

First, we need to install bitcoinjs-lib and axios packages

$ npm i axios && npm i bitcoinjs-lib

bitcoinTransaction.js

This is the module what I make to show you how to send a simple transaction

For making the transaction we need the private key, public key (address) and the last transaction

When we have the transaction hex string we will send them by blockchain.info

The transactions have a commission of 10000 Satoshi in this time are 0,74 USD

const bitcoin = require("bitcoinjs-lib");
const axios = require("axios");
const BITCOIN_DIGITS = 8;
const BITCOIN_SAT_MULT = Math.pow(10, BITCOIN_DIGITS);
const BITCOIN_FEE = 10000;
function getInputs(utxos){
return new Promise(res=>{
let inputs = [];
let utxosCount = utxos.length;
let count = 0;
utxos.forEach(async utxo => {
if (utxo.confirmations >= 6) {
let urlTxes = await axios.get("https://blockchain.info/rawtx/"+utxo.tx_hash_big_endian+"?cors=true&format=hex");
urlTxes = urlTxes.data
inputs.push({
hash: utxo.tx_hash_big_endian,
index: utxo.tx_output_n,
nonWitnessUtxo: Buffer.from(urlTxes, 'hex')
});
count++
if (count === utxosCount){
res(inputs)
}
}
});
})
}
function transaction(privateKey, toPublicKey, fromPublicKey, amount){
return new Promise((resolve, reject) => {
let amtSatoshi = Math.floor(amount * BITCOIN_SAT_MULT);
let bitcoinNetwork = bitcoin.networks.bitcoin;
axios.get("https://blockchain.info/unspent?cors=true&active=" + fromPublicKey).then(async resp=> {
try {
const utxos = resp.data.unspent_outputs
const key = bitcoin.ECPair.fromWIF(privateKey)
let tx = new bitcoin.Psbt(bitcoinNetwork);
let availableSat = 0;
utxos.forEach(input => {
availableSat += input.value;
})

let tx_inputs = await getInputs(utxos);
tx_inputs.forEach(input => {
tx.addInput(input)
});

tx.addOutput({
address: toPublicKey,
value: amtSatoshi
})

tx.addOutput({
address: fromPublicKey,
value: availableSat - amtSatoshi - BITCOIN_FEE
});

tx.signInput(0, key)
tx.validateSignaturesOfInput(0)
tx.finalizeAllInputs()

if (availableSat < amtSatoshi + BITCOIN_FEE) {
reject({ data: "You do not have enough satoshis available to send this transaction."})
return;
}

axios.post('https://blockchain.info/pushtx', { tx: tx.extractTransaction().toHex() }).then( resp => {
resolve({ msg: "Transaction submited", txId: tx.extractTransaction().toHex()})
}).catch( err => {
reject({ data: err.response.data});
})
} catch (err) {
reject({ data: "Error - (87)" });
}
}).catch(err=> {
reject({ data: err.response.data})
});
})

}
module.exports = { transaction };

testTransaction.js

We generate a simple transaction with this test file.

const bitcoinTxs = require("./bitcoinTransaction.js")bitcoinTxs.transaction("MY PRIVATE KEY", "TO ADDRESS", "MY ADDRESS", "MY AMOUNT TO SEND").then(res => {
console.log(res)
}).catch(err=> {
console.log(err)
});

and now we can test it

$ node testTransaction.js

Remember if you have any questions or inquiry tell me, I would be very glad to help you.

Thank you for seeing my post! I hope I’ve been helpful 😁

HAPPY CODING! 👏👏👏👏

    Ivan Cabral

    Written by

    I‘m a daily coder FullStack developer with more than 10 years of experience, creator of gambling web sites, writer for JavaScript and Cryptocurrencies

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade