参考视频: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、部署合约
- 创建一个新的文件夹
mkdir MyDapp2
- 启动
ganache-cli
- 下载web3
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);
- 部署合约
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、调用合约
- 首先创建新工程
express -e contractTest
- 进入工程目录
cd contractTest
进行npm install
npm install web3
- 修改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;
- 修改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;
- 在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>
-
测试能否成功连接web3
npm start
web3较为常用的方法called, send, estimateGas
called:不对参数进行改变的方法
send:修改值(修改区块链的状态)
estimatedGas:通过在本地执行方法,返回消耗值,不进行新的交易
第一个参数ABI,第二个参数是合约地址文章来源:https://www.toymoban.com/news/detail-421951.html -
修改route目录中的index.js文件文章来源地址https://www.toymoban.com/news/detail-421951.html
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;
- 修改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>
- 运行
npm start
至此,视频06结束。
到了这里,关于以太坊Dapp通过web3js部署调用智能合约的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!