Created
May 12, 2018 21:49
-
-
Save levymoreira/fdfb46007cdaaa7cdcaf6b7e13d35018 to your computer and use it in GitHub Desktop.
Sending bitcoin transaction with bitcore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var bitcore = require('bitcore-lib'); | |
var Transaction = bitcore.Transaction; | |
var explorers = require('bitcore-explorers'); | |
var bitcoinaddress = require('bitcoinaddress'); | |
var c2p = require('callback-promise'); | |
const insight = new explorers.Insight('testnet'); | |
var privateKey = bitcore.PrivateKey.fromWIF('cW4r4rajDoKwpEgRPkyF7w7HLaZ7R9zBEDwHtVf2RR1EyBCggESB'); | |
var address = privateKey.toAddress('testnet').toString(); | |
var address2 = 'mz5HhsVBJsY7BFSvbtDefvdvaNzTvmsawp'; | |
const senderWalletTest = { | |
publicKey: address, | |
privateKey: 'cW4r4rajDoKwpEgRPkyF7w7HLaZ7R9zBEDwHtVf2RR1EyBCggESB' | |
} | |
const sendBTC = async (senderWallet, to, amount) => { | |
const unit = bitcore.Unit; | |
const minerFee = unit.fromMilis(0.128).toSatoshis(); // cost of transaction in Satoshis | |
const transactionAmount = unit.fromMilis(amount).toSatoshis(); // convert BTC to Satoshis | |
// Casting callbacks to promises | |
const getUnspentUtxos = c2p(insight, 'getUnspentUtxos', 1, 0); | |
const broadcast = c2p(insight, 'broadcast', 1, 0); | |
const utxos = await getUnspentUtxos(senderWallet.publicKey); | |
const tx = Transaction() | |
.from(utxos) // Feed information about what unspent outputs one can use | |
.to(address2, transactionAmount) // Add an output with the given amount of satoshis | |
.change(address) // Sets up a change address where the rest of the funds will go | |
.fee(minerFee) | |
.sign(privateKey) | |
.serialize(); | |
return broadcast(tx); | |
} | |
const getAddressInfo = c2p(insight, 'address', 1, 0); | |
getAddressInfo(address).then((r) => { | |
console.log(r.balance) | |
}); | |
sendBTC(senderWalletTest, address2, 1) | |
.then((result) => { | |
console.log('Success ', result); | |
}) | |
.catch((err) => { | |
console.log('Error ', err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment