Build serverless apps with Bitcoin - BITBOX / simple-bitcoin-wallet + Webpack

2018-12-07T23:11:51.000Z Honest Cash

I got inspired to write this post during a talk with Chris Troutner about how to include Bitbox into a browser application.

What's BITBOX?

BITBOX is a fully featured javascript framework that you can use for building Bitcoin applications. You don't need to run your own bitcoin node which speeds up the development workflow significantly. Honest integrates Bitbox into the simple-bitcoin-wallet.

Read here why did we build simple-bitcoin-wallet and support Bitcoin Cash exclusively.

We faced a challenge at Honest with the simple-bitcoin-wallet when trying to get it running in a browser. I could not find much help online about it and we made a lot of trial and error until I have got a working version.

TL;DR: To get you started fast, you can simply include simple-bitcoin-wallet by adding the script (1.05MB):

It will expose both SimpleWallet and bitbox on the window object.

Alternatively, you can also add Bitbox Light separately (1 MB):

Personally, I've never seen a simpler way to interact with Bitcoin Cash blockchain than this one:

Minimal Bitbox integration into website

How to build Bitbox for the browser with Webpack?

You can use both the bitbox or bitbox-light for that matter. The light version has been stripped of functionalities that we do not require. You need a "dummy" script importing Bitbox and setting it on the window (global in nodejs) object.

"Dummy" script - bitboxlight.ts

Webpack configuration:

It will package the "dummy" script importing bitbox as a dependency, uglify and minimize it. You will end up with a single file that you can include in your application.

const path = require('path');

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    mode: 'production',
    entry: {
        bitboxlight: './src/bitboxlight.ts'
    },
    output: {
        filename: '[name].min.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: "umd"
    },
    module: {
        rules: [
            {
                test: /\.(js|ts)?$/,
                use: [{
                    loader: 'ts-loader',
                    options: {
                        transpileOnly: true
                    }
                }],
            }
        ],
    },
    externals: {},
    resolve: {
        extensions: [ '*', '.ts' ]
    },
    optimization: {
        minimizer: [new UglifyJsPlugin({
            uglifyOptions: {
                mangle: {
                    keep_fnames: true,
                    reserved: [ "BigInteger", "ECPair", "Point"]
                }
            }
        })]
    },
};

We can run Karma test to confirm that the bitbox has been exported:

Dive into code here

I created a special Github repository for the purpose of this post. Check it out here: https://github.com/honest-cash/bitbox-browser.

Responses