Preparation of Server and web3.js

Published by Mario Oettler on

In this topic, we want to create a small website that uses the web3.js library. It should request information from the blockchain and create a simple transaction that are processed on the blockchain.

What you need:

  • node.js,
  • express,
  • web3.js,
  • browser (Firefox, Brave, or Chrome),
  • MetaMask plugin, and
  • editor

MetaMask is an Ethereum wallet. It manages our private keys and offers a graphical interface for sending transactions. It is installed as a plugin in the browser and allows websites to interact with the blockchain easily. For this purpose, MetaMask connects by default to a full node from Infura. If you like to run your own full node and access it, it is also possible.

In order to enable communication between the website and MetaMask, MetaMask provides the window.ethereum object that can be accessed by Javascript. Here, we use a convenience library like web3.js or ethers.js. Those libraries make it a bit easier to access the ethereum object. But it is also possible to call the ethereum-API directly.

We show both ways.

Preparation – Setting Up the Server

Create a folder for your first project. Navigate to that folder and install node.js and express via npm.

After you set up your working environment, let’s start. Open your JavaScript editor, create a file dapps1_browser01.html and copy the following code.

<!DOCTYPE html>
<html>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

Next, create a file dapps1_server01.js and copy the following code.

var express = require("express");
var path    = require("path");
var app     = express();

app.listen(3000);
console.log("Listening to Port 3000");
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, './','dapps1_browser01.html')); //Pfad ggf. anpassen
});

Save both files and open your terminal/console. Navigate to the project folder and type node dapps1_server01.js.

The terminal should display “Listening to Port 3000”.

Open your browser and enter localhost:3000

This should produce a website that says “Hello World”.

If it doesn’t appear, check your path, file names and express installation.

Preparation – Delivering web3.js

Now that our server is running, we want to deliver our convenience library web3.js to the website.

There are two options:

1. Include it from a content delivery network:

<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>

Or

<script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script>

This is by far the easiest option. If you are not very familiar with web development, you can choose this for learning purposes. The downside of this is that you cannot control if the delivered files are correct or in some way manipulated. If you rely on their integrity, you might want to choose option two.

2. You host your web3.js library on your server and deliver it with every call. We explain this here:

In your project folder, create another folder called public.

Install web3.js via npm and copy the web3.min.js file from the dist folder of the web3 package in the node_modules folder into your new public folder.

Now, we need to tell express to serve the web3.min.js file. This is done with the following line:

app.use(express.static(path.join(__dirname, './', 'public')));

You can use this code.

// Here, we deliver the web3 library to the browser
// We copied the web3.min.js from the dist folder into our project.


var express = require("express");
var path    = require("path");
var app     = express();

app.listen(3000);
console.log("Listening to Port 3000");
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, './','dapps1_browser01.html'));
    app.use(express.static(path.join(__dirname, './', 'public')));
});

Now, we create a tiny website that gives us the actual block number.

In your project folder, create a file dapps1_browser02.html and add the following code.

<!DOCTYPE html>
<html>
    <head>
        <script src='web3.min.js'>
            
        </script>
        <script>
            window.addEventListener("load", (event)=>{
                if(window.ethereum){
                    ethereum.request({method: 'eth_requestAccounts'}).then(function(res){
                        console.log(res);
                        window.web3 = new Web3(window.ethereum);
                        web3.eth.getBlockNumber().then(function(blknr){
                            console.log(blknr);
                            document.getElementById("blockNumber").innerHTML = blknr;
                        })
                    })
                }else{
                    return false
                }
            })
        </script>
    </head>

    <body>
        <h1>My First DApp</h1>
        <div>Blocknumber: </div>
        <div id = "blockNumber"></div>
    </body>
</html>

If you want to try it out, dont’t forget to update the file name in your dapps1_server_02.js file to dapps1_browser02.html.

Now we explain what is inside the source code.

In line 4, we get the web3.js script that we use to interact with MetaMask.

In line 9, we check if MetaMask is installed by checking if the window.ethereum object exists.

In line 10, we connect to an account managed by MetaMask

In line 12, we initialize our Web3 object by passing the window.ethereum object as provider.

In lines 13 to 15, we request the block number and display it in the browser console and on the website.

If you try this out, MetaMask should pop up once the page is loaded. Enter your password and the block number will appear. Make sure that you are connected to the Goerli testnet.

Categories: