Use of Ethereum smart contract NodeJS/Web3

1, Overview

Running environment: Node.js, npm, Truffle, Solidity, etc

  root@keke:~/go-ethereum# node -v
  v8.9.4
  root@keke:~/go-ethereum# npm -v
  5.7.1

solidity installation

# npm install -g solc --save
 Install the development framework Truffle4 of solidity
# npm install -g truffle --save

Install the development client and simulate the running environment of Ethereum locally

When developing truffle 4-based applications, we recommend using EthereumJS TestRPC . It is a complete blockchain in memory, only existing on the device you develop. It returns in real time when the transaction is executed, instead of waiting for the default block out time, so you can quickly verify your newly written code and feed back to you in case of an error. It is also a powerful client that supports automated testing. Truffle 4 takes full advantage of its features and can speed up the test run time by nearly 90%.

The screenshot of the installation of EtherumJS TestRPC is as follows. The red box shows the RPC Server address: http://127.0.0.1 , which will be used in subsequent configurations.

Project initialization

localhost:# mkdir -p truffle4-demo
localhost:#  cd truffle4-demo
localhost:/root/truffle4-demo # truffle init

The project directory structure is as follows:
root@keke:~/truffle4-demo# tree -L 2
.
├── contracts
│   └── Migrations.sol
├── migrations
│   └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js








3 directories, 4 files

New contract

root@keke:~/truffle4-demo# cat contracts/demo.sol
pragma solidity ^0.4.17;

contract Test{
    function sayHi() returns (string){
        return "hello world";
    }
}

Modify migrations / 1 initial migration.js as follows:

root@keke:~/truffle4-demo# cat migrations/1_initial_migration.js 
var Migrations = artifacts.require("./Migrations.sol");

/ /Add custom contract

var demo = artifacts.require("./demo.sol");
module.exports = function(deployer) {
  deployer.deploy(Migrations);
  //Deploy import custom contract
  deployer.deploy(demo);
};

Modify the configuration of truffle.js, as shown in the screenshot:

networks: {
    development: {
        host: "localhost",
        port: 7545,
        network_id: "*"
    }
}

Compile and run contract:

root@keke:~/truffle4-demo# truffle  compile   #The compiled file will be generated in the. / build directory in the format of *. json.
root@keke:~/truffle4-demo# truffle migrate    #Deploy contract to development client
truffle migrate --reset To force recompilation and release of all contracts

Console call contract:

root@keke:~/truffle4-demo# truffle console
truffle(development)> Demo.deployed().then(function(instance){return instance.sayHi.call();});
'hello world'

NodeJS integration Truffle4

Using truffle 4 contract in NodeJS environment requires manual integration of these two modules: Web3 and truffle contract. Before integration, we need to create the npm package management environment of the project. First, enter the Truffle4 demo project directory, and use npm init to initialize the npm package management environment of the project:

root@keke:~/truffle4-demo# npm init     #Generate json configuration file

Install the truffle contract package (when installing the truffle contract package, Web3 will be installed automatically, so there is no need to install the Web3 package again):

root@keke:~/truffle4-demo# npm install truffle-contract --save

Write Node.js calling contract code and create testWeb3.js file in the root directory of the project

//To use Truffle in NodeJS, we need to introduce web3 first
var Web3 = require('web3');
var contract = require("truffle-contract");

//http://localhost:7545 address is the development client address
var provider = new Web3.providers.HttpProvider("http://localhost:7545");

//Use the contract() method of the truffle contract package
//Be sure to use the contents of your compiled Demo.json file
var Demo = contract(
    **Enter here as./build/contracts/Demo.json Content in file**
);

Demo.setProvider(provider);

//No default address, error will be reported
//UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): Error: invalid address
//Be sure to set it to your wallet address. If you don't know, you can view it through the developer client

Demo.defaults({
    from : "0x396FE5d2FA697F62C2C2A8bb48811E87A72D3d03"
});

var instance;

Demo.deployed().then(function(instance){
    return instance.sayHi.call();
}).then(function(result){
    console.log(result);
});

Operation contract:

root@keke:~/truffle4-demo# node testWeb3.js
'hello world'

Tags: npm JSON Blockchain

Posted on Sun, 10 May 2020 23:35:58 -0400 by turtlekid8