官网传送门 Truffle是针对基于以太坊的Solidity语言的一套开发框架。本身基于Javascript,使用以太坊虚拟机(EVM)的世界一流的开发环境,用于区块链的测试框架和资产管道,旨在简化开发人员的生活。
安装truffle
安装前提:
预装nodejs
1.全局安装
npm install -g truffle
建立软链接
ln -s /opt/node-v10.16.0-linux-x64/bin/truffle /usr/local/bin/truffle
2.单个项目安装
npm install truffle
3.查看版本号
truffle version
4.安装成功
构建应用
快速开始 https://www.trufflesuite.com/docs/truffle/quickstart
创建项目
mkdir simple-dapp
初始化项目
truffle init
Note: You can use the truffle unbox <box-name> command to download any of the other Truffle Boxes.
Note: To create a bare Truffle project with no smart contracts included, use truffle init.
本次采用基于webpack的box来构建
truffle unbox webpack
项目目录结构:
- app/:Diretory for app
-
contracts/: Directory for Solidity contracts -
migrations/: Directory for scriptable deployment files -
test/: Directory for test files for testing your application and contracts -
truffle-config.js: Truffle configuration file
创建合约:位于contracts文件夹下
pragma solidity >=0.4.21 <0.7.0; contract Voting { //候选人得票数目 mapping (bytes32=>uint8) public votesReceived; //候选人 bytes32[] public candidateList; //构造器 constructor(bytes32[] memory candidateNames) public { candidateList = candidateNames; } //查询投票数目 function totalVotesFor(bytes32 candidate) view public returns (uint8){ //非空校验 require(validCandidate(candidate)); return votesReceived[candidate]; } //投票 function VotingTo(bytes32 candidate) public { //非空校验 require(validCandidate(candidate)); //add votesReceived[candidate]+=1; } //校验 function validCandidate(bytes32 candidate) view public returns (bool){ for(uint i = 0;i<candidateList.length;i++){ if(candidateList[i]==candidate){ return true; } } return false; } }