This article was first published in the deep and simple blockchain community

Web3 and smart contract interaction actual practice has been updated, please go to the original read

Writing in the front

When you first learned about Ethereum, many people created their own Ethereum nodes and used Geth to interact with them. This approach to command-line interaction excites many programmers (Matrix deja vu?). But you can’t expect the average user to use Dapp from the command line. Therefore, we needed a friendly way (such as a Web page) to interact with the smart contract, and the answer was web3.js.

Web3.js

Web3.js is an official ethereum Javascript API that allows smart contract developers to interact with local or remote Ethereum nodes using HTTP or IPC. In fact, it is a collection of libraries, mainly including the following libraries:

  • web3-ethTo interact with the Ethereum blockchain and smart contracts
  • web3-shhUsed to control the Whisper protocol to communicate with P2P and broadcast
  • web3-bzzUsed to interact with the Swarm protocol
  • web3-utilsContains some useful features for Dapp development

Web3 communicates with GETH using JSON-RPC, which is a lightweight Remote Procedure Call (RPC) protocol. The whole communication model can be abstracted as the following figure.

Build test chain

At the beginning of development, there was no need to use a real public chain. For the sake of development efficiency, we usually set up a test chain locally. In this paper, we choose Ganache (testrPC was used before, Ganache is an upgraded version of it), a graphical testing software (also has command line version), which can build the ethereum blockchain test environment locally with one click, and display the status of the blockchain through a graphical interface. The running interface of Ganache is shown in the following figure.

As shown in the figure, Ganache creates 10 accounts by default. The listening address is http://127.0.0.1:7545, and you can view Current Block, Gas Price, Gas Limit, and other information in real time.

Create smart contracts

Currently, ethereum officially fully supports the smart contract development environment is Remix IDE. We wrote the following code in the contract editing page:

pragma solidity ^0.421.;

contract InfoContract {
    
   string fName;
   uint age;
   
   function setInfo(string _fName, uint _age) public {
       fName = _fName;
       age = _age;
   }
   
   function getInfo() public constant returns (string, uint) {
       return(fName, age); }}Copy the code

The code is very simple, simply assign and read the name and age variables, then switch to the TAB of run, change the Environment into Web3 Provider, and enter the address of our test chain http://127.0.0.1:7545. Here’s a quick explanation of the three options:

  • Javascript VM: simple Javascript virtual machine environment, pure practice smart contract writing time can choose
  • Injected Web3: Connect to Web3 embedded in the page, such as to MetaMask
  • Web3 Provider: Connects to custom nodes, such as private test networks.

If the connection is successful, the Account option below defaults to the address of the first Account created by Ganache. Next we click Create to deploy our smart contract into our test network. Keep the Remix page open, and use the address of the contract and ABI information when writing the front-end code later.

Install the Web3

To do this, create our project in terminal:

> mkdir info
> cd info
Copy the code

Next, use node.js’s package management tool NPM to initialize the project and create a package.json file that holds the relevant dependency environments required by the project.

> npm init
Copy the code

Press Enter all the way until the project is created. Finally, run the following command to install web.js:

> npm install web3
Copy the code

Note: in the process of actual installation I found web3 after installation is complete and no/node_modules/web3 / dist/we3. Min. Js file, this problem is evident in the issue# 1041, but the official like hasn’t been solved. However, you can download the required files here, unzip the dist folder and copy it to /node_modules/web3.

To create the UI

Create index.html in the project directory. Here we will create the basic UI, including name and age input fields, and a button, which will be implemented using jQuery:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="main.css">

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

</head>
<body>
    <div class="container">

        <h1>Info Contract</h1>

        <h2 id="info"></h2>

        <label for="name" class="col-lg-2 control-label">Name</label>
        <input id="name" type="text">

        <label for="name" class="col-lg-2 control-label">Age</label>
        <input id="age" type="text">

        <button id="button">Update Info</button>


    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

    <script>
       // Our future code here..
    </script>

</body>
</html>
Copy the code

Next you need to write a main.css file to set the basic styles:

body {
    background-color:#F0F0F0;
    padding: 2em;
    font-family: 'Raleway'.'Source Sans Pro'.'Arial';
}
.container {
    width: 50%;
    margin: 0 auto;
}
label {
    display:block;
    margin-bottom:10px;
}
input {
    padding:10px;
    width: 50%;
    margin-bottom: 1em;
}
button {
    margin: 2em 0;
    padding: 1em 4em;
    display:block;
}

#info {
    padding:1em;
    background-color:#fff;
    margin: 1em 0;
}
Copy the code

Once the UI is created, write the web.js code in the middle of the

<script> if (typeof web3 ! == 'undefined') { web3 = new Web3(web3.currentProvider); } else { // set the provider you want from Web3.providers web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545")); } </script>Copy the code

This code is a sample provided by Web3.js Github, which means that if Web3 is already defined, it can be used directly as our provider. If not, we specify the provider manually.

The question may arise here: why was Web3 defined in advance? In fact, if you use software like MetaMask (a Chrome plugin that is a mini Ethereum wallet), the provider will be automatically embedded.

Next set the default Ethereum account based on the code above:

web3.eth.defaultAccount = web3.eth.accounts[0];
Copy the code

We have already created 10 accounts with Ganache in the above article, so we choose the first account as the default account.

Next we need to let web3 know what our contract looks like, using the contract’s ABI (Application Binary Interface). The ABI lets us call the functions of the contract and get data from the contract.

We have created our contract in Remix above, now we go back to Remix, under Compile TAB we click Details on the page that appears, we can copy the ABI of the contract, as shown in the picture below.

varinfoContract = web3.eth.contract(PASTE ABI HERE!) ;Copy the code

Next, go to the TAB of Run and copy the address of the contract into the following code:

var info = InfoContract.at('PASTE CONTRACT ADDRESS HERE');
Copy the code

Once we’ve done that, we can call the functions in the contract. Here we use jQuery to interact with our contract:

info.getInfo(function(error, result){
    if(! error) { $("#info").html(result[0] +'('+result[1] +' years old)');
            console.log(result);
        }
    else
        console.error(error);
});

$("#button").click(function() {
    info.setInfo($("#name").val(), $("#age").val());
});
Copy the code

This code simply implements calls to the two functions in the contract, reading and displaying the name and age variables, respectively.

At this point we have completed the entire code, which can be found in InfoContract. Open index.html in a browser and test the result as shown below (refresh after entering name and age).

The author of this article is Gai Gai, whose wechat account is ChainLab

reference

  • Interacting with a Smart Contract through Web3.js (Tutorial)

Dynamic And Simple Blockchain – Learn blockchain systematically and build the best blockchain technology blog.

Dynamic Planet Of My Knowledge answers blockchain technology questions. Welcome to join the discussion.

Aid To The Public account “Deep And Simple Blockchain Technology” To obtain blockchain technology information for the first time.