参考视频:https://www.bilibili.com/video/BV14z4y1Z7Jd?p=1
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;
}
}
mkdir MyDapp2
ganache-cli
npm install web3
,注:ganache的启动和deploy.js要在同一个目录。node deploy.js
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
web3.eth.getAccounts().then(console.log);
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);
});
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;
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;
<!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>
测试能否成功连接web3npm start
web3较为常用的方法called, send, estimateGas
called:不对参数进行改变的方法
send:修改值(修改区块链的状态)
estimatedGas:通过在本地执行方法,返回消耗值,不进行新的交易
第一个参数ABI,第二个参数是合约地址
修改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;
<!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>