Tutorials

Websockets Scaffold

Intro

Websockets make possible an entirely new generation of apps which depend on real-time data. BITBOX SDK has websockets built in. Our new scaffold enables you to bootstrap a Bitcoin Cash React app with BITBOX and websockets integration in under a minute. Accelerate your workflow with BITBOX Scaffolds.


@porlybe created Donate BCH, which shows the power of websockets and let's you bootstrap your next great app. It's powered by BITBOX and lets you display logos and QR codes for donations.

Websocket scaffold homepage

When a donation is made a modal appears showing the amount.

EatBCH donation

EatBCH_S S donation


Scaffold

We created a scaffold from Donate BCH to quickly let you bootstrap a React app w/ BITBOX and websockets with no further setup. First run the new command and pass in the --scaffold websockets flag.

bitbox new donateBCH --scaffold websockets

websocket scaffold

Next cd into donateBCH, install the deps and start the app.

cd donateBCH
npm install
npm start

Edit src/donation.js to add donation addresses, locations and logos. Both legacy and cash addresses are valid. You can add new logos to src/assets/.


Leveraging BITBOX

Donate BCH shows very practical ways to leverage BITBOX when creating an app. It demonstrates unit and address conversion, calling REST and listening on a websocket.

Unit Conversion

BITBOX can convert whole BCH units to satoshis as well as converting satoshis to bits and back to whole units. The scaffold converts satoshis to whole BCH.

const value = BITBOX.BitcoinCash.toBitcoinCash(curr.satoshi)

Address Conversion

BITBOX has methods for converting cash address to legacy and legacy to cash. The scaffold converts cash address to legacy address.

const cashaddr = BITBOX.Address.toCashAddress(address)

REST

BITBOX SDK has REST integration bundled. The scaffold calls Address.details to get back utxo for an address.

BITBOX.Address.details(addr).then(
  result => {
    result.forEach(r => {
      Object.keys(donations).forEach(p => {
        if (p === r.legacyAddress)
          donations[p].balance = (r.unconfirmedBalance + r.balance).toFixed(8)
      })
    })
    this.setState({
      donations,
    })
  },
  err => {
    console.log(err)
  }
)

Socket

The Socket class lets you quickly get real-time blockchain data. First create an instance and then call listen. Here's how the scaffold updates the UI after new tx data comes in.

const socket = new BITBOX.Socket()
socket.listen('transactions', this.handleNewTx)

Summary

BITBOX SDK has websockets built in which enables real-time data in Bitcoin Cash apps. Our websocket scaffold lets you bootstrap a Bitcoin Cash React app with BITBOX and websockets integration in under a minute.

Share on...