Bitcoin Cash for web developers, demo using the browser only

6 218
Avatar for FreelanceForCoins
5 years ago

If you're a web developer and Bitcoin Cash seems a bit hard to understand, then let me show you how to accept Bitcoin Cash from yourself, send Bitcoin Cash to random strangers and send the change back to you. All in your browser, simple HTML and JS.

You will also understand how to accept, send, monitor Bitcoin Cash on your site if you want to build on top of Bitcoin Cash.

All you need is a regular desktop browser (won't work that well on mobile, since there's no developer tools). Brave is used in the article. Chrome, Chromium, Firefox will work the same.

Getting to the browser console

Open a new tab.
Type about:blank in the address field and hit Enter.
Right click the empty space.
Click Inspect.
Click Console.

That's probably the hardest part of the article.

Add the script tag

First of all we need to load a script. It's the same as adding this to a HTML page.

It's a picture so that you don't accidentally paste it. It won't work in the console.

It's a compiled script (we'll explain at the end of the article) and you can find its source here: https://read.cash/simple-wallet/src/index.js (we will get back to this source in a bit)

Paste this into the console:

const script = document.createElement('script');
script.setAttribute('src', 'https://read.cash/simple-wallet/dist/wallet-0.1.js');
document.head.appendChild(script);
You should see this

Creating a wallet

Let's create a brand new Bitcoin Cash wallet in your browser. It will disappear when you close your browser.

First we need to define some variables, don't worry about them yet, we'll explain.

Paste this:

const mnemonic = null;
const derivationPath = "44'/145'/0'";
const derivationNode = "0/0";

Now let's create a new wallet.

Paste this:

wallet = new BCHWallet('bitcoincash', mnemonic, derivationPath, derivationNode);
console.log(`If you want to backup your wallet - it's mnemonic is: ${wallet.mnemonic}`);

bitcoincash here is the name of the network. You can use testnet for TestNet network (where tokens are free), but as of this moment the TestNet API by bitcoin.com is down. So, we're going to play with the real Bitcoin Cash money!

If you want to test on TestNet (and it works) - then replace 'bitcoincash' in the code above to 'testnet'.

You should see this.

Congratulations! You now have a Bitcoin Cash wallet. And you also have access to mine too now. "Mnemonic" words give you full control of it.

Let's send some money to this wallet

Let's send some Bitcoin Cash to this address and wait for it to arrive. I'll use the (async ()=>{ ... })() syntax here. You can just ignore it, the important part is inside, for example:

Example of what's important.

Paste this into your console:

let originalSourceCashAddress;
(async () => {
    console.log(`Send some Bitcoin Cash on ${wallet.network} network to ${wallet.cashAddress}`);
    const tx = await wallet.waitForTx();
    console.log(`Got the transaction ${tx}`);
    const details = await wallet.BITBOX.Transaction.details(tx);
    originalSourceCashAddress = details.vin[0].cashAddress;
    console.log(`It came from ${originalSourceCashAddress}`);
})();

If you don't have any Bitcoin Cash - you can go to https://free.bitcoin.com/ and get some real Bitcoin Cash for free. You only need to have Google Account.

If you're testing on TestNet (see first steps) - the TestNet faucet is here: https://developer.bitcoin.com/faucets/bch/

Here's what you're going to see. I'll send money from my Electron Cash:

Cool, now we have some Bitcoin Cash in our wallet. Woo-hoo!

What's the balance of our wallet?

Paste this:

(async () => {
    const balanceSat = await wallet.balanceSat();
    console.log(`The new balance is ${balanceSat} satoshis ` + 
        `or ${wallet.satToBch(balanceSat)} BCH ` + 
        `or $ ${(await wallet.satToUsd(balanceSat)).toFixed(2)}`);
})();
Awesome! Our 1 cent has arrived!

Here's the fun part - we'll take one cent, send something to two strangers and we'll have something to send back to our original wallet!

Let's send some Bitcoin Cash to some strangers

Ok, let's send our 600 satoshis (1 "satoshi" is 1 / 100 millionth of Bitcoin Cash) to one random stranger and 700 sats to another one

How much is it?

Paste this:

(async () => {
    console.log(`$ ${(await wallet.satToUsd(600))}`);
})();
So, 600 satoshi is less than 1 US cent.

Let's send it!

Paste this:

(async () => {
    const toAddrSats = [
        // stranger1 gets 600 sat
        ['bitcoincash:qqrxa0h9jqnc7v4wmj9ysetsp3y7w9l36u8gnnjulq', 600],
        // stranger2 gets 700 sat 
        ['bitcoincash:qpk4hk3wuxe2uqtqc97n8atzrrr6r5mleczf9sur4h', 700],
    ];
    const tx = await wallet.send(toAddrSats);
    console.log(`Sent ${tx}!`)
})();

Awesome! Two happy strangers now have $0.001 more! You can even check your transaction on a block explorer.

Let's send the rest of the money back!

If our first code we've created a variable originalSourceCashAddress which contains the original address from where the money came. Let's send the rest back!

Paste this:

(async () => {
    const tx = await wallet.sendMax(originalSourceCashAddress);
    console.log(tx);
})();

If everything goes according to the plan:

Let's get to the details of what happened

Well, actually if you look at the code you've been pasting - you now have enough to implement some basic functionality of Bitcoin Cash on your site. Generate wallets for users, wait for transactions, send money somewhere else. All without banks, approvals and permissions.

Add this to your HTML file:

<script src="https://read.cash/simple-wallet/dist/wallet-0.1.js"></script>

(well, at least copy it to your server first, don't rely on us holding it forever)

Create new wallet?

const mnemonic = null;
// or recover our demo wallet by using
// const mnemonic = 'mother brick uphold taxi word diet night exhibit gospel claim try alien';
const derivationPath = "44'/145'/0'";
const derivationNode = "0/0";
wallet = new BCHWallet('bitcoincash', mnemonic, derivationPath, derivationNode);

Want to wait for transactions?

const tx = await wallet.waitForTx();

Want to send money? It's as simple as:

const tx = await wallet.send([ [cashAddress, satoshis], ]);

Send money to two addresses?

const tx = await wallet.send([ [cashAddress, satoshis], [cashAddress2, satoshis2], ]);

tx is short for Transaction ID.

Get balance?

const balanceSat = await wallet.balanceSat();

How does it work? It's actually a simple script, like we mentioned - the source is here:
https://read.cash/simple-wallet/src/index.js

Look into that file - it's pretty simple.

It loads bitbox-sdk(bitcoin.com library) and adds a simple class to window:

The whole file is just 200 lines.

And then defined the simple class Wallet. The whole file is just 200 lines and it has all the most common things you need, like send:

You can now take the relevant parts and use them.

How does bitbox-sdk work? It uses https://rest.bitcoin.com/ to interact with Bitcoin Cash blockchain.

Why do we have dist/ and src/ files?

I'm talking about this:

https://read.cash/simple-wallet/dist/wallet-0.1.js
https://read.cash/simple-wallet/src/index.js

The problem is that you can't just add a <script> tag with bitbox-sdk from bitcoin.com - you need to have node installed and do this:

put it into src/index.js file to build a <script src="...">-suitable script

If you do this and then run (assuming you have node.js installed):

npx webpack --mode "development"

You'd get dist/index.js file which you can load as

<script src="dist/index.js"></script>

<script>
var BITBOX = new BITBOXSDK({restURL: 'https://rest.bitcoin.com/v2/'})
</script>

We need to use --mode "development" to preserve some names. Usually it's not the recommended way.

That's not possible without node.js. That's why we created the dist/ script - to be able to show it in your browser.

Here's more info how to use BITBOX: https://developer.bitcoin.com/bitbox/

The Wallet class that we wrote just shows some simple patterns of how to do things.

1-minute explanations of mnemonic, derivation path and node

The only thing you need to know about mnemonic is that those are words that are converted to big number, which is the master private key for a series of wallets.

Now if you add a derivation path 44'/145'/0'/0/0 you can get one private key and public key, there is one more at 44'/145'/0'/0/1 and 44'/145'/0'/0/2 and so forth. The first part 44'/145'/0' is called "derivation path" and Bitcoin Cash typically uses this one (44'/145'/0'), the second is typically called "node" (0/0).

If somebody knows your mnemonic - they can spend all money at all those "nodes".

This is a very basic 1-minute explanation. Google for "HD wallet bitcoin" to get more detailed information on these terms.

5
$ 0.63
$ 0.50 from @Telesfor
$ 0.08 from @sanctuary.the-one-law
$ 0.05 from @Archie
Avatar for FreelanceForCoins
5 years ago

Comments

Wow thanks so much for bringing us such an educating tips

$ 0.00
4 years ago

Fantastic, well composed write up

$ 0.00
4 years ago

Wow that is a very cool article. I will definitely have a look at all the other ones. Dont know why I've never seen that content. I guess mobile backyard photography is more relevant and important... :/

$ 0.00
4 years ago

Wow, good learning field

$ 0.00
4 years ago

A very educating article. This can promote BCH in practical ways to woo new users of BCH. However, one needs to revise the processes very well to avoid flaws while demonstrating the game.

$ 0.00
4 years ago

Thanks for this! I'm going to try and build something powered by BCH!

$ 0.00
4 years ago