以太坊Dapp开发通过web3.js调用智能合约

在dapp目录下创建一个工程sixtest

[root@ dapp]# express -e sixtest

我们在remix当中部署好的智能合约

pragma solidity ^0.4.22;

contract  counter{
    uint256 counter;

    constructor() public{
        counter = 1;
    }

    function getCounter()public view returns(uint256){
        return counter;
    }

    function changeCounter(uint256 a) public{
        counter += a;
    }

}

以太坊Dapp开发通过web3.js调用智能合约_第1张图片以太坊Dapp开发通过web3.js调用智能合约_第2张图片

进入到sixtest目录下进行npm install操作

我们还需要进行安装web3

npm install web3 -save

修改routes目录下的index.js

var express = require('express');
var router = express.Router();

var Web3 = require('web3');
var web3 =  new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

web3.getAccounts().then(console.log);

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;              

修改目录下的app.js文件 vim app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();


var ejs = require('ejs');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html',ejs.__express);
app.set('view engine', 'html');
//app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');

module.exports = app;

在sixtest目录下的views当中创建index.html文件,并且将index.ejs复制到其中。



  
    <%= title %>
    
  
  
    

<%= title %>

Welcome to <%= title %>

测试是否能成功

[root@ sixtest]# npm start

> [email protected] start
> node ./bin/www

[
  '0x930518c17201051A2C9a820c242F205f87767f06',
  '0x652945236a3d96e631f95c9373Fc5d0774Ae2e92',
  '0xbf4f91f8D7cb564e6d016DDA6a65BC5eDbacf902',
  '0xD79a65Dc80bE92625D739e7daC05a361D9BeaF9E',
  '0x8544049B57803e0a190445F268Fb3e7A3D307cED',
  '0xb1a518Ca38F9532230ae982703eEC3844249E772',
  '0xb24aCF61a30bcb618da8e27E57eC5167892E21A1',
  '0xf02cFF084d416CD89057a067385ee8312DB51022',
  '0x52B8600BB62938Fc461006BdE4a3c34A2914c5A4',
  '0xBc07537f4E016FB3341728390285D271fefB48ce'
]

证明成功连上web3.js

现在进一步修改routes当中的index.js文件
**当中的代码段来源于web3.js开发手册当中的web3.eth.Contract中的new contract 创建一个新的合约实例:
var myContract = new web3.eth.Contract([…], ’ ', {
from: ‘0x1234567890123456789012345678901234567891’, // default from address
gasPrice: ‘20000000000’ // default gas price in wei, 20 gwei in this case
});
第一个[…]参数是智能合约的ABI,也就是下图当中的内容
第二个参数 ’ ’ 是你部署合约的地址 就是上一节以太坊Dapp开发通过web3.js部署合约当中最后的Contract address。
以太坊Dapp开发通过web3.js调用智能合约_第3张图片

ar express = require('express');
var router = express.Router();

var Web3 = require('web3');
var web3 =  new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

// web3.eth.getAccounts().then(console.log);


**var myContract = new web3.eth.Contract([
        {
                "constant": false,
                "inputs": [
                        {
                                "name": "a",
                                "type": "uint256"
                        }
                ],
                "name": "changeCounter",
                "outputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
                        },
        {
                "inputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "constructor"
        },
        {
                "constant": true,
                "inputs": [],
                "name": "getCounter",
                "outputs": [
                        {
                                "name": "",
                                "type": "uint256"
                        }
                ],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
        }
], '0x2247fdbC867ab4A6fb85787Daa0c12B9aB27FB60');**



//myContract.methods.getCounter().call({from: '0x652945236a3d96e631f95c9373Fc5d0774Ae2e92'}, function(error, result){
//     console.log("counter:",result);
//});

var init_counter = 0;
var current_counter = 0;

myContract.methods.getCounter().call().then(function(counter){
     console.log('init counter:',counter);
     init_counter = counter;

});
/* GET home page. */
router.get('/', function(req, res, next) {
myContract.methods.changeCounter(5).send({from: '0x652945236a3d96e631f95c9373Fc5d0774Ae2e92'})
.then(function(){
     myContract.methods.getCounter().call().then(function(counter){
     console.log('current counter:',counter);
     current_counter = counter;
     res.render('index', {init:init_counter,current:current_counter });
        });
   });
});

module.exports = router;

接下来我们来修改views当中的index.html



  
    调用智能合约
    
  
  
    

init:<%= init%>

current:<%= current%>

最后我们来看一下效果
在sixtest目录下运行npm start命令
出现以下结果

[root@ sixtest]# npm start

> [email protected] start
> node ./bin/www

init counter: 1

此时在浏览器中打开http://127.0.0.1:3000
以太坊Dapp开发通过web3.js调用智能合约_第4张图片
此时也会出现我们的current

[root@ sixtest]# npm start

> [email protected] start
> node ./bin/www

init counter: 1
current counter: 6
GET / 200 208.813 ms - 211
GET /stylesheets/style.css 200 32.996 ms - 111

你可能感兴趣的:(以太坊Dapp,linux,npm,dapp)