当前位置:首页 » 《随便一记》 » 正文

以太坊Dapp开发通过web3.js调用智能合约_柠檬味小发糕的博客

8 人参与  2022年04月06日 15:24  分类 : 《随便一记》  评论

点击全文阅读


在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;
    }

}

在这里插入图片描述在这里插入图片描述

进入到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复制到其中。

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>

测试是否能成功

[root@ sixtest]# npm start

> sixtest@0.0.0 start
> node ./bin/www

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

证明成功连上web3.js

现在进一步修改routes当中的index.js文件

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

<!DOCTYPE html>
<html>
  <head>
    <title>调用智能合约</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>init:<%= init%></h1>
    <h1>current:<%= current%></h1>
  </body>
</html>

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

[root@ sixtest]# npm start

> sixtest@0.0.0 start
> node ./bin/www

init counter: 21

此时在浏览器中打开http://127.0.0.1:3000在这里插入图片描述此时也会出现我们的current

[root@ sixtest]# npm start

> sixtest@0.0.0 start
> node ./bin/www

init counter: 21
current counter: 26
GET / 200 196.958 ms - 213
GET /stylesheets/style.css 304 204.034 ms - -


点击全文阅读


本文链接:http://m.zhangshiyu.com/post/37467.html

目录下  修改  文件  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1