开发目标:
去中心化的宠物商店
知识储备:
HTML、JavaScript、CSS
Web服务器
智能合约
Web3.js //和智能合约进行交互
开发流程:
新建项目(初始化)
合约编写
合约编译、部署、测试
合约交互
开发工具:
VS code/Atom/Sublime
Truffle/Ganache
MetaMask
环境搭建:
先安装Nodejs 5.0+: https://nodejs.org/en/
在cmd中输入$ npm install -g truffle
Truffle官网:https://truffleframework.com/
cmd中:
C:\Users\Tai Park>mkdir pet-shop
C:\Users\Tai Park>cd pet-shop
C:\Users\Tai Park\pet-shop>truffle init
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!
Commands:
Compile: truffle compile
Migrate: truffle migrate
Test contracts: truffle test
C:\Users\Tai Park\pet-shop>dir
驱动器 C 中的卷是 OS
卷的序列号是 06EA-4DF7
C:\Users\Tai Park\pet-shop 的目录
2018/08/06 10:30 <DIR> .
2018/08/06 10:30 <DIR> ..
2018/08/06 10:30 <DIR> contracts
2018/08/06 10:30 <DIR> migrations
2018/08/06 10:30 <DIR> test
2018/08/06 10:30 545 truffle-config.js
2018/08/06 10:30 545 truffle.js
2 个文件 1,090 字节
5 个目录 129,899,622,400 可用字节
下载 Ganache:https://truffleframework.com/ganache
在VSCode中打开pet-shop文件夹。
其中contracts文件夹用来放置所有的智能合约的代码。
在contracts中新建Adoption.sol进行智能合约的编写。
pragma solidity ^0.4.0;
contract Adoption{
address[16] public adopters;
function adopt(uint petId) public returns(uint){
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}
function getAdopters() public view returns (address[16]) {
return adopters;
}
}
在VSCode中利用查看->集成终端 呼出终端,并利用truffle compile编译智能合约:
C:\Users\Tai Park\pet-shop>truffle compile
Compiling .\contracts\Adoption.sol...
Compiling .\contracts\Migrations.sol...
Writing artifacts to .\build\contracts
若报错请参考:https://blog.csdn.net/qq_36329973/article/details/81452127
若编译成功会生成build文件夹,内含Adoption.json来描述智能合约的情况。
下面开始部署合约,放在migrations文件夹下。
新建文件2_deploy_contracts.js
复制文档中的内容:https://truffleframework.com/docs/getting_started/migrations
var Adoption = artifacts.require("Adoption");
module.exports = function(deployer) {
// deployment steps
deployer.deploy(Adoption);
};
打开Ganache找到Server地址。在truffle.js中配置:
module.exports = {
networks:{
development:{
host:"127.0.0.1",
port:7545,
network_id:"*"
}
}
};
在cmd中:
C:\Users\Tai Park\pet-shop>truffle migrate