read.cash Log in
@FreelanceForCoins edited

Bitcoin Cash for web developers, demo using the browser only 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 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);

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'`.

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:

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)}`); })();

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))}`); })();

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. https://explorer.bitcoin.com/bch/tx/11bce09358b679ef1d5e0404fa4c9bde0060b29f046ebb0bf1e3cd7112acd690 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`:

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:

If you do this and then run (assuming you have node.js installed): https://nodejs.org/en/download/ 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. https://nodejs.org/en/download/ 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.

63¢

4 comments

Log in to join in Reading is open to everyone. Replying needs an account.