Blockchain & Solidity Program Lab Manual
ISBN 9788119221646

Highlights

Notes

  

Prog. 22:

Smart Contract using Web3.js

Using the web3.js APIs

we shall create a folder named web3projects to store the web3.js

APIs. In Terminal, type the following commands:

$ cd ~

$ mkdir web3projects

$ cd web3projects

Before you download the web3.js APIs, you want to create an empty Node.js project:

$ npm init –yes

The preceding command creates a file named package.json. This file contains the 
dependencies required by a Node.js application. To download the web3.js APIs, type the 
following command:

$ npm install web3@0.20.7 --save

The --save option informs npm to modify the package.json file and add the web3.js

as a dependency for the application.

Create a text

file named TestWeb3.html and save it in the web3projects folder.

Populate it as follows:

<!DOCTYPE html>

<html lang=“en”>

<script src=“./node_modules/web3/dist/web3.min.js”></script>

<body>

<script>

if (typeof web3!== ‘undefined’) {

// this statement is executed if you are using

// MetaMask

async function enableAccounts() {await ethereum.enable();

.then((account) => {

alert(“Account: “ + account + “\n” + “Provider Name: “ + web3.currentProvider.constructor.name);

})

}

enableAccounts();

} else {

// set the provider you want from Web3.providers web3 = new Web3(

new Web3.providers.HttpProvider(“http://localhost:8545”));

alert(“Account: “ + web3.eth.accounts[0] + “\n” + “Provider Name: “ + web3.currentProvider.constructor.name);

}

</script>

</body>

</html>

In Terminal, type the following command:

$ npm install -g serve

In the web3projects folder, type the following command:

$ serve

Using the Chrome browser (with MetaMask installed), load the following URL: 
http://localhost:5000/TestWeb3.html.

Click Connect

You need to give permission to the page to allow it to access your

MetaMask account(s)