escrow-bitcoin
Version:
A service to make possible escrow transactions using BTC (Bitcoin)
41 lines (39 loc) • 1.61 kB
JavaScript
const explorers = require('bitcore-explorers');
const bitcore = require("bitcore-lib");
/**
* Make a bitcoin transaction
*
* @param {Address} addressFrom - Address to withdraw
* @param {PrivateKey} privateKeyFrom - PrivateKey from Address to withdraw to sign transaction
* @param {Address} addressTo - Address to send
* @param {Number} amount - Amount (in satoshis)
* @param {Networks} [network=bitcore.Networks.testnet] - Network to make transaction
* @returns string (transaction id)
*/
function Transaction(addressFrom, privateKeyFrom, addressTo, amount, network = bitcore.Networks.testnet) {
return new Promise(function (resolve, reject) {
const insight = new explorers.Insight(network);
insight.getUnspentUtxos(addressFrom, function (err, utxos) {
if (err) {
reject(err)
} else {
if (utxos.length == 0) {
return reject(new Error("if no transactions have happened, there is no balance on the address"))
}
var transaction = new bitcore.Transaction()
.from(utxos)
.to(addressTo, amount)
.change(addressFrom)
.sign(privateKeyFrom);
insight.broadcast(transaction, function (error, body) {
if (error) {
reject(error)
} else {
resolve(body)
}
});
}
});
})
}
module.exports = Transaction;