以太坊区块链入门之实现简单DApp开发

以太坊区块链入门之实现简单DApp开发,第1张

前期准备

本dapp是采用ganache-cli的私链开发,用express来创建项目,web3js来连接私链

//安装ganache-li
sudo npm install -g ganache-cli
//安装solidity(我刚开始用的是npm install solc报错,最后使用snap成功安装)
sudo snap install solc
//web3j安装
sudo npm install web3 -save
若web3js始终安装报错,请见博主另外一篇博客https://blog.csdn.net/holy19__/article/details/122609600启动ganache-cli(会自动分配十个用户)
创建工程 安装express
//express安装
sudo npm install -g express-generator

!!!警示!!! 一定要在该工程目录下(若是题主则是dapp目录下)重新安装web3,否则项目将无法成功创建

创建工程
express -e Dapp1



在创建成功后会出现如上提示,接下来跟着提示走即可

 cd Dapp1
npm install
npm start

最后在浏览器输入: 127.0.0.1:3000
出现以下则表示该项目创建成功:

合约编写+部署 合约编写
合约编写使用的是remix在线编程工具
remix在线工具地址:https://remix.ethereum.org/
合约代码(由于该篇博客只是为了阐明dapp开发的基本流程):
pragma solidity >=0.4.22 <0.8.0;

contract Counter{
    uint256 conter;
    constructor() public{
        conter=1;
    }
    function kinCounter(uint step) public{
        conter+=step;
    }
    function getCounter() public view returns(uint256){
        return conter;
    }
}
部署合约
1、 创建一个合约部署目录,目录下创建一个js文件
2、目录下一定得安装web3(博主建议直接在前面创建项目的目录下即dapp目录下创建合约部署目录,这样就不需要再重新安装web3)
3、首先创建deploy目录(注意该目录是和Dapp1同级的)
4、再创建deploy.js文件
5、向deploy.js文件里添加代码:
(代码中从var counterContract = new web3.eth.Contract开始之后所有的代码就是合约的部署代码,是Remix自动生成的,在remix中自动编译后找到如图WEB3DEPLOY的地方,直接复制再粘贴至js代码中即可,注意将 arguments: [ ]
}).send({ from:’’ }内from后的序列改为ganache用户的地址)
6、使用node deploy.js运行deploy.js即可部署成功

remix中WEB3DEPLOY位置:

**//具体deploy.js代码**
 	var Web3=require('web3');
console.log("test");
var web3=new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
console.log(web3.version);
web3.eth.getAccounts().then(console.log);
var counterContract = new web3.eth.Contract([{"constant":true,"inputs":[],"name":"getCounter","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"step","type":"uint256"}],"name":"kinCounter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]);
counterContract.options.data="0x608060405234801561001057600080fd5b50600160005560b1806100246000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80638ada066e146037578063fef527c314604f575b600080fd5b603d606b565b60408051918252519081900360200190f35b606960048036036020811015606357600080fd5b50356071565b005b60005490565b60008054909101905556fea265627a7a72315820bacf3927d6966aa5031c2e52312113c304cd7bd953f13d79ef0dc962335174e264736f6c634300050b0032"
var counter = counterContract.deploy({
     data: '0x608060405234801561001057600080fd5b50600160005560b1806100246000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80638ada066e146037578063fef527c314604f575b600080fd5b603d606b565b60408051918252519081900360200190f35b606960048036036020811015606357600080fd5b50356071565b005b60005490565b60008054909101905556fea265627a7a72315820bacf3927d6966aa5031c2e52312113c304cd7bd953f13d79ef0dc962335174e264736f6c634300050b0032',
     arguments: [
     ]
}).send({
     from: '0x3878Ef8A312B8B108D634e6D5A56789afE11edbC',
     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("address:",contract.options.address);
 })

部署成功页面:

调用合约 进入第一步创建的Dapp1工程
修改/routes/index.js文件,代码如下:
(js文件具体解释请查看下面代码的注释)
 var express = require('express');
var router = express.Router();
var Web3=require('web3');
var web3=new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
//var myContract=new web3.eth.Contract([],'');
//该代码的第一项为remix内合约编译后的ABI,remix内ABI的位置同WEB3DEPLOY位置基本一致,具体看代码后的图,直接复制即可
//第二项参数为合约地址,在部署合约时deploy.js内打印在控制台里的,直接复制即可
var myContract=new web3.eth.Contract([
	{
		"constant": false,
		"inputs": [
			{
				"internalType": "uint256",
				"name": "step",
				"type": "uint256"
			}
		],
		"name": "kinCounter",
		"outputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "getCounter",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	}
],'0xE3Aa5983ac9E570Ed76Ef6B2E32534792AB53c6C');
//调用合约的getCounter()函数,from后面的地址为ganache启动的用户地址
myContract.methods.getCounter().call({from:'0xb309Aad4cC50e0fea2af70068aD7a45F297fE3EC'},
function(error,result){
	console.log("conter:",result);
});
var init_counter=0;
var current_counter=0;

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

});
/* GET home page. */
router.get('/', function(req, res, next) { 
//调用合约kinCounter()函数,from后面的地址为ganache启动的用户地址
myContract.methods.kinCounter(3).send({from:'0xb309Aad4cC50e0fea2af70068aD7a45F297fE3EC'})
  .then(function(){
 myContract.methods.getCounter().call().then(function(counter){
	console.log('cure:',counter);
	current_counter=counter;
	res.render('index', { init: init_counter,curent: current_counter});
});
  });
});
module.exports = router;

修改app.js文件
用如下代码替换原app.js文件中
的这部分内容
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');

替换后:

在views目录下新建html文件
html代码如下:
 

  
    diaoyongheyue
    'stylesheet' href='/stylesheets/style.css' />
  
  
    init number: <%= init %>
    curent number: <%= curent %>
  

该代码中的init,current与/routes/index.js中getCounter()方法内的res.render(‘index’, { init: init_counter,curent: current_counter});的这句代码里的init,current对应。

页面显示

在浏览器输入 http://127.0.0.1:3000出现如下页面

以上就是一次web3js和express实现简单dapp开发的基本流程啦!!!!!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/929265.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-17
下一篇 2022-05-17

发表评论

登录后才能评论

评论列表(0条)

保存