Sending Bitcoin programmatically using BlockCypher API

BlockCypher provides convenient REST APIs to send cryptocurrency like Bitcoin easily. Here are two APIs that we can use to send Bitcoin from one address to another:

1. Build transaction skeleton https://api.blockcypher.com/v1/btc/test3/txs/new 2. Push signed transaction https://api.blockcypher.com/v1/btc/test3/txs/send

Here are the step by steps of using those APIs in JavaScript (Node.js) in testnet3 Bitcoin network. First, create a POST request (request package is used in this example) to the first API to build transaction skeleton by passing the from address, to address and Bitcoin amount (converted to Satoshis):

request.post(
{ 
    url: 'https://api.blockcypher.com/v1/btc/test3/txs/new', 
    body: JSON.stringify({ inputs: [{ addresses: [ from ] }], 
    // convert amount from BTC to Satoshis 
    outputs: [{ addresses: [ to ], value: amount * Math.pow(10, 8) }] }),
}, 
function (err, res, body) {
    // process result 
});

Under the hood, this API takes care quite complex tasks, such as:

  • Calculates transaction fees based
  • Calculates and includes unspent (previous) transaction(s) based on given amount

Then, on successful request, the first API will return a TX Skeleton object that needs to be signed.

To sign it, we need to use from address WIF (Wallet Import Format [https://en.bitcoin.it/wiki/Wallet_import_format]) to sign the transaction:

// convert response body to JSON
let tmptx = JSON.parse(body); 

// attribute to store public keys 
tmptx.pubkeys = [];

// build signer from WIF 
let keys = bitcoin.ECPair.fromWIF(wif, bitcoinNetwork); 

// iterate and sign each transaction and add it in signatures while store corresponding public key in pubkeys 
tmptx.signatures = tmptx.tosign.map(function (tosign, n) {
  tmptx.pubkeys.push(keys.getPublicKeyBuffer().toString('hex'));
  return keys.sign(new Buffer(tosign, 'hex')).toDER().toString('hex');
});

Finally, send signed transaction object tmptx to Bitcoin network using second API. You can keep the final transaction object if you like. But in this example we just return the transaction hash which can be looked up in network explorer such as https://live.blockcypher.com/btc-testnet/:

request.post({ 
  url: 'https://api.blockcypher.com/v1/btc/test3/txs/send',
  body: JSON.stringify(tmptx), 
}, 
function (err, res, body) { 
  if (err) { 
    reject(err); 
  } else {
    // return tx hash as feedback 
    let finaltx = JSON.parse(body);
    resolve(finaltx.tx.hash);
  } 
}); 

That’s all. You can find full code of the function here. Cheers! 🍻

Leave a Reply

Your email address will not be published. Required fields are marked *