Getting started with blockchain as a Web2.0 developer
Published: 2024-03-26 10:30:39

You want to start using blockchain but it feels very intimidating. You thought about it and started by learning about what a blockchain is, how it works, the cryptography, the consensus and all theoretical concepts. Soon you are too deep into it and still don’t know how to actually use it.
Remember the first time you wanted to use a database. Did you start with deep diving into how the database was implemented(storage, indexes)? Like many others, you probably started by learning how to use it (schema, table, query). When you started to use it, you probably started to go deeper to understand how it works, and then it made a lot of sense.
I want to take the same approach to blockchain and in doing so I will be drawing analogies from traditional software development (though sometimes not precisely). I will not answer many “Why” questions, that’s for a later article. I will be using the Tezos blockchain for all example codes.

**What Can I Use the Blockchain for?**

Consider blockchain as a server in the cloud that you can use. You can use it to:
1. Store data 
2. Run your code 

This means you can run code to do some computation, store state and interact with that state.

**What is this all Crypto-currency about?**

At the end of the day, storing data and running code needs to happen on someone’s physical machine, so when you store your data and run your code, The person who owns the physical machine occur some operating costs, hence it shouldn’t be free for you and the person who owns the physical machine should get paid for. Hence there is an economic system built around it, generally referred to as gas/ gas cost. To pay for this “gas” you need to spend a currency, every blockchain has a native currency and this is the currency you use to pay the cost of gas. This is cryptocurrency!

For Tezos the native currency is called Tez and the gas cost is generally calculated in the millionth of a tez (called mutez). 

This is similar to paying for a cloud service based on the data you store and the code you run

**What Do I need to get started**

To do anything on a blockchain, you will have to have the following:

1. An account 
2. Some currency balance in that account.

_Create an account_

To create an account you will need a wallet.

Now what is a wallet? The wallet is an application that helps you manage your accounts and helps you interact with the blockchain. It’s like a password manager plus an authenticator app rolled into one.

Account works by public-private key cryptography. Your private key is used to sign any operation so that it can be verified that you are the one who signed the operation.

You can use the [Temple wallet](https://templewallet.com/download)

Note down the account number(typically starting with tz1), we will use it later.

_Get some currency_

If you want, you can buy cryptocurrency, but for exploration purposes we will use the test environment, called ghostnet.
The sandbox works similarly to the real blockchain and is used for testing purposes. Here you can get some “free” 
“cryptocurrency.”This currency is limited to the sandbox and has no value in the main blockchain.

You can use a “faucet” to get some free Tez for ghostnet. You can use a service like [this](https://faucet.ghostnet.teztnets.xyz/).

_Enough of setup, how do I use it?_

Let’s write the simplest possible code to interact with the blockchain. 

Install node js if you haven’t already. 
(You will need Node version 18 or above to run this code, as fetch was natively available in Node from 18 onward. for lower versions, you can install node-fetch and modify the code to import it.)

```javascript
async function getBalance(address) {
   var networkUrl = 'https://ghostnet.smartpy.io/';
   var url_path = 'chains/main/blocks/head/context/contracts/${address}/balance';
   var url = networkUrl + url_path.replace('${address}', address);
   var response = await fetch(url);
   var balanceInMutez = await response.json();
   var balanceInTez = balanceMutez / 1000000;
   return balanceInTez;
}

var address = 'YOUR_FIRST_ACCOUNT'
var balance = await getBalance(address);
console.log(balance + " ꜩ");
```

Now let’s understand the code. This is similar to calling a REST API. The main aspects that you need to understand are as follows:

**URL**
The RL is similar to a REST API URL where you are getting looking for a resource 

**Request**
The code is  making a get request to get the resource 

**Response**
The code is getting a response for the resource balance.  
This was simple but we actually didn’t do much. Let’s try our hand at something more complex. How about we send some crypto to another account? What does it entail to send crypto to another account?

- Prepare the data for operation 
- Convert it to bytes
- sign these bytes with your 1st account 
- Then create (“inject”) an operation by creating a POST request to /injection/operation with signed bytes of data for operations

As you can see this is a lot of work to hand-code everything. Luckily there is a library that can be very helpful. Let’s configure this library now

Create your project folder and install this library with node
npm install @taquito/taquito

Create a file Transfer.ts and add the following code

```javascript
import { TezosToolkit } from '@taquito/taquito';
import { RemoteSigner } from '@taquito/remote-signer';

const Tezos = new TezosToolkit('https://ghostnet.smartpy.io');
```
Import your private key (this should only be done for testing and learning, we will learn how to do it “right” way later). Get the key from the wallet. You can use the instructions shown [here](https://youtu.be/qVQoyVIvLVQ) and load key in memory 

```javascript
Tezos.setProvider({
 signer: new InMemorySigner('YOUR_PRIVATE_KEY_FOR_FIRST_ACCOUNT'),
});
```

Do a transfer
```javascript
const amount = 2;
const address = 'YOUR_SECOND_ACCOUNT';

console.log(`Transfering ${amount} ꜩ to ${address}...`);
Tezos.contract
 .transfer({ to: address, amount: amount })
 .then((op) => {
   console.log(`Waiting for ${op.hash} to be confirmed...`);
   return op.confirmation(1).then(() => op.hash);
 })
 .then((hash) => console.log(`Operation injected: https://ghost.tzstats.com/${hash}`))
 .catch((error) => console.log(`Error: ${error} ${JSON.stringify(error, null, 2)}`));
```

The full code should look like this.

```javascript
import { TezosToolkit } from '@taquito/taquito';
import { InMemorySigner, importKey } from '@taquito/signer';

const Tezos = new TezosToolkit('https://ghostnet.smartpy.io');
Tezos.setProvider({
 signer: new InMemorySigner('YOUR_PRIVATE_KEY'),
});

const amount = 2;
const address = 'tz1h3rQ8wBxFd8L9B3d7Jhaawu6Z568XU3xY';

console.log(`Transfering ${amount} ꜩ to ${address}...`);
Tezos.contract
 .transfer({ to: address, amount: amount })
 .then((op) => {
   console.log(`Waiting for ${op.hash} to be confirmed...`);
   return op.confirmation(1).then(() => op.hash);
 })
 .then((hash) => console.log(`Operation injected: https://ghost.tzstats.com/${hash}`))
 .catch((error) => console.log(`Error: ${error} ${JSON.stringify(error, null, 2)}`));

```

With this you are ready to use the blockchain in your application. In the next article we will talk about running your code in blockchain and storing data in blockchain.