参考视频:https://www.bilibili.com/video/BV14z4y1Z7Jd?p=1

1、在线编译智能合约

https://remix.ethereum.org/
在这里插入图片描述

pragma solidity ^0.4.0;

contract MyCounter{
    uint256 counter;

    constructor() public {
        counter = 1;
    }

    function kipCounter(uint step) public{
        counter +=step;
    }
    function getCounter() public view returns (uint256){
        return counter;
    }
}

2、部署合约

  1. 创建一个新的文件夹mkdir MyDapp2
  2. 启动ganache-cli
  3. 下载web3npm install web3,注:ganache的启动和deploy.js要在同一个目录。
  4. 先进行测试node deploy.js
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

web3.eth.getAccounts().then(console.log);
  1. 部署合约
    web3的版本:1.7.1
    复制 WEB3DEPLOY 的内容到deploy.js
    == ganache需要启动才能运行 ==
    在这里插入图片描述
    修改
    from: web3.eth.accounts[0],成ganache对应的账户
var mycounterContract = new web3.eth.Contract([{"constant":true,"inputs":[],"name":"getCounter","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"step","type":"uint256"}],"name":"kipCounter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]);


var mycounter = mycounterContract.deploy({
     data: '0x608060405234801561001057600080fd5b50600160008190555060e7806100276000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638ada066e14604e578063e24801d8146076575b600080fd5b348015605957600080fd5b50606060a0565b6040518082815260200191505060405180910390f35b348015608157600080fd5b50609e6004803603810190808035906020019092919050505060a9565b005b60008054905090565b806000808282540192505081905550505600a165627a7a72305820948660862b007e09bde5dcec9d432c7caced4dff0a50ed85f6f1af784b50ed750029', 
     arguments: [
     ]
}).send({
     from: '0x0bfb484EB4B451FC20F52cDa3FF366097858C69A', 
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 }).then(function(contract){
 console.log("Contract address:",contract.options.address);
 });

合约地址每次启动都会变化
最终结果:
在这里插入图片描述

3、调用合约

  1. 首先创建新工程express -e contractTest
    在这里插入图片描述
  2. 进入工程目录cd contractTest进行npm install npm install web3
  3. 修改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;
  1. 修改route目录下的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.eth.getAccounts().then(console.log);

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

module.exports = router;
  1. 在view的目录下新建index.html
<!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>

  1. 测试能否成功连接web3npm start
    在这里插入图片描述
    web3较为常用的方法called, send, estimateGas
    called:不对参数进行改变的方法
    send:修改值(修改区块链的状态)
    estimatedGas:通过在本地执行方法,返回消耗值,不进行新的交易
    在这里插入图片描述
    在这里插入图片描述
    第一个参数ABI,第二个参数是合约地址

  2. 修改route目录中的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.eth.getAccounts().then(console.log);

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

//调用合约
//可以指定从哪个账户发出,则任意选一个账户
// myContract.methods.getCounter().call({from: '0xe23493eACdC904cfd5826f9775Ee22B881051630'}, 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. */
//修改counter的值,并传递该参数
router.get('/', function(req, res, next) {
    myContract.methods.kipCounter(5).send({from: '0xe23493eACdC904cfd5826f9775Ee22B881051630'})
    .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;

  1. 修改view里的index.html
<!DOCTYPE html>
<html>
  <head>
    <title>调用合约</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>调用合约</h1>
    <p>init counter: <%= init %><br>current counter:<%=current %></p>
  </body>
</html>
  1. 运行npm start
    在这里插入图片描述在这里插入图片描述
    至此,视频06结束。
Logo

为所有Web3兴趣爱好者提供学习成长、分享交流、生态实践、资源工具等服务,作为Anome Land原住民可不断优先享受各种福利,共同打造全球最大的Web3 UGC游戏平台。

更多推荐