Building Applications On Bitcoin — Part 1: Bitcoin|Computer & Smart Contracts with JavaScript

Zachary Weiner
7 min readOct 16, 2020
Use javascript to create smart contracts on the bitcoin blockchain

Programing for the blockchain is hard.

ETH has some wonderful tools to make it easier to get started like metamask and w3.js. But, building on Ethereum, comes with some major complexities. Even as you move to overcome them, you’re left with being forced to choose between two crappy flavors of ice cream: Running your own full node, or using Metamask as an in-browser intermediary.

Looking to build on Bitcoin as an application layer like Solidity is on ETH becomes even more difficult. Bitcoin scripts, OP_Codes, Buffers, preImage… these aren’t the building blocks that most programmers (read: web/app developers) are familiar with.

Enter Bitcoin Computer

Clemens Ley has a special skill for boiling complex computing systems into simple analogies that even my mother could understand. Looking at how difficult the coding stack is, and how wasteful Ethereum is (it replicates every smart contract operation across all of its miners), he built a solution as simple as his explanation.

Using JavaScript as the foundation Clemens built Bitcoin|Computer so that JavaScript developers could forget about learning ByteCode, OP_Codes, and input/output scripts, and focus on building their application from the start.

There are solutions like this for cloud — we call them Backend as a Service or Data as a Service. In code they’re called libraries or frameworks.

Why should developers have to learn machine code? They shouldn’t. We write JavaScript, Python, Ruby or C#… and we do it well! Now, for 90% of use cases we can use BitcoinComputer to get the job done, client side, with no nodes or servers at all. You can choose to host your application at a web address (aka on a server), but it could also be an APK or PWA that runs directly on a local machine without any ‘server’ what-so-ever.

Building A Bitcoin App Step 1:

Get An Account & Some Test Coins.

Before you can get started building, you’re going to need an account. In blockchain terms thats called a wallet. In the real world a wallet can have different folds or sleeves. In the blockchain world those ‘folders’ are represented by an Address. The analogy to a real world ‘address’ holds up very well. It is essentially a marker on a map, that you own, and can put your stuff (house, shed, cars, safe) on or in.

An address is just a string of seemingly random numbers and letters. Instead of the address you might find on a map like:
104 Soundtree lane

On the blockchain it might be: ‘dsjbfbv73i9KUH…’

Those crazy looking letters & numbers are just a shorter name (an ‘also known as’) for a public/private key pair, which are annoyingly also crazy random strings of lettters and numbers. They’re just longer, and held to a different standard than Addresses.

What is a Public/Private Key pair? You can think of it like a padlock. The public key is what you send out to other people to lock up your stuff, before shipping your stuff back to you. Your Private key is like the 17–23–08 code you use to unlock the padlock and get your stuff from the shipment.

Your PublicKey is always different than your PrivateKey. This way you can send your public key out without having to share your private key with anyone else.

Why Do I Need An Address aka Public/PrivateKey aka Seed aka Wallet?

We will be saving data on Bitcoin ‘inside’ of a transaction. That means every time you want to allow someone to use your application to store a move in a game, or change a cell in a spreadsheet, a transaction is created on the blockchain that saves what you’ve chosen to store.

The Bad News: You have to pay the miners to make sure it gets on to the record.

The Good News: Luckily the going rate is about 1 satoshi per byte and trending down.

You need a little bit of BitcoinSV or BitcoinABC in it in order to write anything to the blockchain. If you didnt think you’d have to be paying for this tutorial… you’re in luck. We’re gonna run this on TestNet for free.

Step 1 — Part 1: How Do I Get A Totally New And Random Seed?

Getting an account is as easy as making up 12 words.

Using 12 words that are important to you isn’t a good plan. We want each one of them to be random.

Side note: Words might not seem like the most secure way to go, but with more than 2000 accepted words for use in your 12 word phrase, the combination possibilities are nearly endless.

2000 multiplied by 2000, 12 times then again 4 times for each of the 4 languages supported means there are more combinations of words than there are grains of sand on the planet earth.

To get a seed phrase at the click of a button, you can visit

accounts.protoshi.com
or
bitcoin-react-base.herokuapp.com

Neither uses a server to generate the seed, it happens client side and never leaves your browser.

But, if you would like to generate your own in code, here’s how it works:

How To Generate A Seed Phrase For BSV in JavaScript (if you want)

If you need to install node.js google: ‘How to install node.js’ :)

  1. Create a new folder on your computer
  2. Navigate to the folder in your console
  3. type the command % npm init -y
  4. type the command % npm install bsv
  5. type the command % npm install bip39
  6. create a file called mybsv.js with the contents
let bsv = require('bsv');
let Mnemonic = require('bsv/mnemonic');
let bip39 = require('bip39')
//get your random 12 words
let seed_phrase = Mnemonic.fromRandom().toString();
console.log("Your new random Seed Phrase is: " + seed_phrase);//turn your 12 word phrase into a privateID that Bitcoin can use
const seed = bip39.mnemonicToSeedSync(seed_phrase);
let hdPrivateKey = bsv.HDPrivateKey.fromSeed(seed, bsv.Networks.testnet);
// A public ID for making an address is a property of the privateKey
let publicKey = hdPrivateKey.publicKey;
//get an address that we can use to send the wallet money (Bitcoin)
let address = bsv.Address.fromPublicKey(hdPrivateKey.publicKey);
//Print The Address on Screen
console.log("Your Address is: " + address.toString());

6. type the command % node mybsv.js

7. Save Your Seed Phrase and Your Address in a file. (dont save live credentials like this… the code above uses testnet)

Step 1 — Part 2: Get Free Bitcoins For Testing.

Head over to https://faucet.bitcoincloud.net.

Use the address you created above in the text box on the page. Complete the Captcha, and click the Roll Button.

If you followed all the steps you’ll have some Satoshis in your address.

If you just want to check that the satoshi’s made it to your address, you can use your seed phrase to sign in to any wallet that supports test net. One such application that uses the test network by default is:
http://bitcoin-react-base.herokuapp.com

Clemens’ Bitcoin|Computer github repo has a number of simple examples you can clone and run locally to check your balance as well.

Now that you have some satoshis, and an account lets get started building!

Step 2: Create React App || Create Vue && Add Bitcoin|Computer

At the time of this writing Bitcoin|Computer is at release 0.4.2-beta.

You can install Bitcoin|Computer via npm install or yarn add, but I’ve noticed the process is a little more smooth if we add Bitcoin|Computer to the package.json file manually, and force npm to create a new lock file.

For this tutorial we are going to use React but you can choose to use Vue (personally tested that it works)

For a great tutorial on getting started with React: https://reactjs.org/docs/create-a-new-react-app.html

Once you get your app running and launched to localhost, open up the package.json file and add the line: (you may want to check if theres been a release)

"bitcoin-computer":"^0.4.1-beta"

Then delete the package.json.lock file and the npm_module folder and in a terminal/command prompt run: npm install

Assuming you get no errors lets just go ahead and test that the references are installed properly. First open up your App.js file and replace it with the following code:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Computer from 'bitcoin-computer'
function App() {
const send = async (e) => {
e.preventDefault()
const computer = new Computer({
seed: "your seed phrase here ",
chain: "BSV", // BSV or BCH
network: "testnet" // testnet or livenet
})
console.log('async starting')
const address = await computer.db.wallet.getAddress()
console.log("Address", address.toString())
console.log(await computer.db.wallet.getBalance())
const pubKey = computer.db.wallet.getPublicKey()
console.log("TX:", await computer.db.wallet.send(parseInt(1, 10), pubKey));
console.log("send completed")
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<form onSubmit={send} >
<button type='submit'>Send</button>
</form>
</div>
);
}
export default App;

Then on line 11 replace “your seed phrase here” with your seed phrase inside quotes.

Fire up a console/termial and type: npm start

You should be able to visit the application at localhost:3000. If the page loads properly without error, you should see a button on the bottom of the page that says “Send”

Bring up the developer tools in the broswer and select console.

Click the “Send” Button on the page, and watch the output of the bitcoin computer initialization + transfer of 1 satoshi back to your own account.

If the transaction goes through as expected, the console will log

“TX: ksnfnn3nfksdy6bfas8…”

Copy the transaction ID beginning after TX:

Navigate to test.whatsonchain.com, paste the transaction ID into the search box and hit enter. You should see your transaction on chain!

And just like that you’ve built a JavaScript application that runs locally without a central server, and communicates an instruction to send money from one account to another! WOAH!

--

--

Zachary Weiner

Founder @MagicDapp.io & @AlphaDapp.com | Find @DevelopingZack on Twitter & Telegram