参考教程:https://www.bilibili.com/video/BV14z4y1Z7Jd?p=8
本博客是学习Dapp开发过程的笔记,感谢令狐一冲老师精彩讲解。上述是老师B站视频链接。
Ganache
ganache是一个本地区块链环境,每次启动后会在内存中模拟一个区块链。
1.环境安装
1.安装Node.js
2.安装 ganache-cli(ganache也可以)
3.运行ganache
ganache-cli
!!Truffle
安装truffle
sudo npm install -g truffle
安装过程中可能出错,可能解决方式
//升级node.js
sudo npm install -g n
sudo n stable
安装完成之后检查安装
truffle -v //版本
开发DApp(投票为例)
1.编写智能合约
投票合约
// SPDX-License-Identifier: SimPL-2.0
pragma solidity >=0.4.18 <0.8.0;
contract Voting{
bytes32[] public candodateList;
mapping(bytes32 => uint8) public votesReceived;
constructor(bytes32[] memory _candidateListName) public {
candodateList = _candidateListName;
}
function validateCan(bytes32 _candidate) internal view returns(bool) {
for(uint8 i = 0; i< candodateList.length; i++) {
if(candodateList[i] == _candidate)
return true;
}
return false;
}
function voteForCan(bytes32 _candidate) public {
votesReceived[_candidate] += 1;
}
function totalVotes(bytes32 _candidate)public view returns(uint8) {
return votesReceived[_candidate];
}
}
2.创建项目
mkdir Voting
cd Voting
truffle unbox webpack
//webpack 可以换成其他的模板文件,也可以换成init不用模板
//遇到问题了,
/*
✔ Preparing to download box
✖ Downloading
Unbox failed!
✖ Downloading
Unbox failed!
Error: Error connecting to github.com. Please check your internet connection and try again.
*/
//也可以通过如下方式获取
git clone https://github.com/truffle-box/webpack-box.git
$ cd truffle-init-webpack
3.修改合约部署脚本
1.启动ganache
删除模板里其他合约,将自己的合约部署到ganache上
2.修改合约部署脚本
修改migration中的2_deploy+contract.js(照着葫芦画瓢)
// const ConvertLib = artifacts.require("ConvertLib");
// const MetaCoin = artifacts.require("MetaCoin");
const Voting = artifacts.require("Voting"