Chapter 8. What Is Web3?

Web3 is a collection of JS libraries that lets you interact with an Ethereum node remotely or locally. Simply, it provides us with an API to use so we can easily work with the blockchain. Web3 works as a wrapper for JSON RPC to connect to a remote or local Ethereum node with either a HTTP or IPC connection. Web3 is basically a connection between the Ethereum blockchain and your smart contract.

Behind the scenes, Web3 uses JSON RPC. RPC is used in many different types of programming languages. You can learn more about JSON RPC here. This chapter focuses on Web3 because Web3 makes connecting to an Ethereum node less complicated and much easier to understand than RPC.

The Frontend, Web3, and the Blockchain

In a traditional web 2.0 application, your user will interact with the frontend of an application such as React or Ember to make a request to the backend that will have databases, APIs, and models, which will then return a response from the backend. The frontend will serve up the data from the backend to the frontend, and the frontend will display it to your user.

The flow of a web 2.0 application is illustrated in Figure 8-1.

Connection between Traditional Frontend and Backend
Figure 8-1. Connection between a traditional frontend and backend

If you have experience in traditional web development, Web3 is similar to an API request that is getting or adding data to the backend. But with Web3, you’ll be reading and writing data to the blockchain instead of a traditional backend.

Your user will interact with the frontend of your application such as React, which will then use Web3 to make a request that connects to the blockchain. Web3 will interact with the blockchain through RPC and provide the response to the frontend, which you will then render to the user.

A Web3 application flow will look like Figure 8-2.

Connection between Web3/Frontend/blockchain
Figure 8-2. The connection between Web3, frontend, and backend

We’ll take a look at a few of the methods to interact with the blockchain that we can use and that are made available from Web3 in the next section.

Web3 Methods

Web3 offers many methods that we can use to interact with the blockchain. We’ll use these methods to read or write data to the blockchain from our React application. We can send ether from your address to another address, call methods, get the balance of a blockchain address, get gas costs, and more. We’ll use these methods later when we connect our application to an Ethereum node.

Let’s start by taking a look at a few examples of Web3 methods.

getAccounts()

The getAccounts() method can be used to return a list of your Web3 wallets.

It’s important to note that getAccounts will only return your unlocked wallets. This might trip you up later, so always remember to Google error messages and follow this book carefully.

web3.eth.getAccounts()

getBlockNumber()

The getBlockNumber method will return the current block number.

web3.eth.getBlockNumber()
> 8911

getBalance()

getBalance can be used to get the balance of the account you pass in as an argument. We’ll use this later on when we connect our contracts to React, the frontend framework we’ll be using.

Here’s an example of using the getBalance method to find the balance of this address:

web3.eth.getBalance
web3.eth.getBalance("0xa589BDa5379fDE626dD3eBF462fA22F5dfF43f30")
    .then(console.log);

Here is the result:

"2000000000000"

sendTransaction()

If we wanted to send funds from one address to another, we would use sendTransaction to do it.

web3.eth.sendTransaction()

Here’s an example of sending funds from one account to another:

web3.eth.sendTransaction({
    from: "0xa589BDa5379fDE626dD3eBF462fA22F5dfF43f30",
    to: "0xa289BDa5379fDE626dM3eBF462fA22F5dfF43f31",
    value: web3.toWei(1, "ether"),
})

The from param is the account you want to transfer the funds from. The to param is the account that you want to send the funds to. The value param is the amount of ether that you will send from the sender address to the receiver address.

Tip

Never try to write your address from another source. Always copy and paste when sending funds. It won’t matter if you lose some test ether, but it will matter if you accidentally transfer real funds. Also always be sure to double-check that the address is correct before you send funds.

If we want to use Web3, we have to set a provider so Web3 knows which node to connect to:

web3.setProvider

We’ll use this method later on when we set up a React application to work with our contracts.

For now, while we’re developing locally, we’ll set our provider to localhost. If we want to connect to our localhost, we’ll set our provider to localhost:8545 as shown in the following example:

new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))

We’ll use some of these Web3 methods later on when we build larger applications. Next, we’ll learn exactly what a provider is.

Providers

A Web3 provider will tell your project which node you’ll talk to. Simply, it’s how your project can talk to the blockchain. This can be compared to the URL you might use to make an API call to in a traditional web application. The provider will send our RPC instructions to the correct Ethereum node.

There are various different ways to link to a running node. A provider links to a running node such as Parity or Geth. Once you’re connected through a provider, the node can interact with the blockchain.

Later in the DApp we’ll build, we’ll connect to our provider as in the following. We’ll call Web3 and set the provider for our application so our users can interact with the blockchain.

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'))

If we wanted to check the current provider, we can use web3.currentProvider, which will return the current provider if we are using one and null if no provider exists.

Next, let’s learn about how we can make a request to the blockchain and see the result returned through a promise.

Promises with Web3

We’ll use promises quite a bit with Web3. Promises are a concept where something may or may not return a value in the future. We can attach a callback to a promise, which will either return an error if it does not resolve.

If we need to make multiple calls, promises are the best solution because they allow us to return the result or an error. If we wanted to use the getBalance() function to see a user’s balance, we would use the following:

return new Promise (function (resolve, reject) {
    web3.eth.getBalance("0xa589...", function (error, balance) {
      if (error) {
        reject(error)
      } else {
        resolve(balance)
    }
  })
}

Without a promise, the call would not return the proper value. Here’s a more complicated example of a web3.js file that uses promises, which you would use to set up Web3 with your application. We’ll use this later to interact with Web3 and our frontend.

import Web3 from 'web3'

let getWeb3 = new Promise(function(resolve, reject) {
  window.addEventListener('load', function() {
    var results
    var web3 = window.web3

    if (typeof web3 !== 'undefined') {
      web3 = new Web3(web3.currentProvider)

      results = {
        web3: web3
      }

      resolve(results)
    } else {
      var provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545')

      web3 = new Web3(provider)

      results = {
        web3: web3
      }

      resolve(results)
    }
  })
})

export default getWeb3

In the preceding code snippet, we’re first waiting for our page to load with our promise. After we have Web3, we’ll use resolve(results) to view our promise results.

If we don’t have a Web3 injection, we’ll use an else statement and set it to a localhost and use Web3 locally. http://127.0.0.1:9545 would be your own port, which is set up with your application.

Next, let’s learn about MetaMask and how we’ll interact with Web3 applications through it. We previously set it up in the book, but now let’s learn about how we’ll use it in the application in this book.

MetaMask for Web3 Injection

MetaMask is a browser extension that allows us to easily interact with websites that use Web3. MetaMask manages your Ethereum accounts and private keys. It’s like a wallet but in your browser instead.

MetaMask will store your ether and let you sign transactions and pay gas fees. It also provides a very convenient way for users to interact with your Web3 application without running their own node. Refer back to the installation chapter for more information about MetaMask.

But how do we interact with the blockchain? We’ll use the next method, send, to interact with the blockchain and open a MetaMask popover. Let’s discuss the send method and how we can write to the blockchain with it.

Send (State Updates/Write)

The other type of method we’ll use with Web3 is the send method. Your DApp will need to use the send method whenever you want to add to the blockchain. You’ll see later when we set up our frontend for our DApp that the send method requires your user to use MetaMask, sign the transaction, and pay gas fees.

We’ll use the send method for times that we need to alter the blockchain.

Next, let’s learn about a less intrusive method: call. The call method does not cost gas, and it’s used for methods where we might want to get the result of something in a contract. The send method forwards gas, so it is more invasive than the call method.

Call (Reads)

Call is used for view and pure functions.

While the send method will prompt your user to use MetaMask, the call method won’t prompt your user to sign anything with MetaMask, and it won’t cost any gas. Note that the call method is also safer to use because it doesn’t forward gas. It also won’t create a transaction on the blockchain, so it’s safer to use because it’s not publishing anything.

The return value is returned immediately and is a read-only function. Due to this, the call method is also faster. We’re going to use the call method a lot in this book because it’s fast and it won’t cost any gas or transaction fees.

Summary

In this chapter, we’ve learned that Web3 is a collection of JS libraries that allow us to connect to an Ethereum node. Web3 is a wrapper for JSON RPC, and provides us an API we can use in our applications to interact with the blockchain in a simple way. We’ve learned about how Web3 is different from a traditional web 2.0 application.

We’ve also learned about how our frontend will connect to Web3, which will transfer data with the blockchain. And we’ve learned a few Web3 methods, such as call and send, which we’ll begin to use in the next chapter.

In the next chapter, we’ll work on connecting a smart contract to a UI. We will use Web3 in our React application to connect and interact with the blockchain.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset