Skip to content

Instantly share code, notes, and snippets.

@levymoreira
Created May 5, 2018 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levymoreira/0bb56f0e92a6f6452cf7014b2284d480 to your computer and use it in GitHub Desktop.
Save levymoreira/0bb56f0e92a6f6452cf7014b2284d480 to your computer and use it in GitHub Desktop.
send tx bitcoin
var bitcoin = require("bitcoinjs-lib");
var axios = require("axios");
const TestNet = bitcoin.networks.testnet;
// https://testnet.manu.backend.hamburg/faucet
// https://testnet.coinfaucet.eu/en/
// https://testnet.blockexplorer.com/address/n2AxiA2Fd7y4spAciPXKUxKFpEPezpyRzR
const run = async () => {
// generate
// var keyPair = bitcoin.ECPair.makeRandom({ network: TestNet });
// console.log('levy2', keyPair.getAddress());
// console.log('levy3', keyPair.toWIF());
// From n2AxiA2Fd7y4spAciPXKUxKFpEPezpyRzR
var keyPair1 = bitcoin.ECPair.fromWIF('cW4r4rajDoKwpEgRPkyF7w7HLaZ7R9zBEDwHtVf2RR1EyBCggESB', TestNet);
console.log('levy4', keyPair1.getAddress());
console.log('levy5', keyPair1.toWIF());
// To mz5HhsVBJsY7BFSvbtDefvdvaNzTvmsawp
var keyPair2 = bitcoin.ECPair.fromWIF('cNurxkqx9zifbnVR7HgPGwSjDcZVhYeUCTzpwBHKhjCq6TbT4RML', TestNet);
console.log('levy4', keyPair2.getAddress());
console.log('levy5', keyPair2.toWIF());
// https://blockchain.info/unspent?address=
let apiUrl = 'https://testnet.blockexplorer.com/api/addr/'
// log unspent transactions
const utxo = await axios.get(apiUrl + keyPair1.getAddress() + '/utxo');
console.log(utxo.data);
// log balance
const balance = await axios.get(apiUrl + keyPair1.getAddress() + '/balance');
console.log(balance.data);
// Transaction
let tx = new bitcoin.TransactionBuilder(TestNet);
let amountWeHave = balance.data // 1.1 BTC
let amountToKeep = balance.data - 100000000 //200000000 // 1 BTC
let transactionFee = 1000 // .00001 BTC
let amountToSend = amountWeHave - amountToKeep - transactionFee
tx.addInput(utxo.data[utxo.data.length - 1].txid, 0);
tx.addOutput(keyPair2.getAddress(), amountToSend);
tx.addOutput(keyPair1.getAddress(), amountToKeep);
tx.sign(0, keyPair1); // 0 refers to the first input
let tx_hex = tx.build().toHex();
var txDecoded = bitcoin.Transaction.fromHex(tx_hex);
var txid = txDecoded.getId();
console.log(`********* TX - ${txid} **********`);
console.log(tx_hex);
console.log('*******************');
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment